美文网首页
linux 安装 nginx

linux 安装 nginx

作者: 行走的蛋白质 | 来源:发表于2023-05-16 17:00 被阅读0次

安装

  • 在 CentOS 上,可直接使用 yum 来安装 Nginx
    yum install nginx -y
  • 扩展: 卸载用 yum remove nginx

启动

  • 安装完成后,使用 nginx 命令启动 Nginx (如果无法访问,请重试用 nginx -s reload 命令重启 Nginx)
    nginx
  • 此时访问服务器 IP 就可以看到 Nginx 的测试页面了

配置

  • 外网用户访问服务器的 Web 服务由 Nginx 提供,Nginx 需要配置静态资源的路径信息才能通过 url 正确访问到服务器上的静态资源
  • Vim 编辑器打开 /etc/nginx/nginx.conf 找到 server
    • 将 server_name 改为服务器ID
    • root 改为静态资源路径, 比如 /code/dist
# 全局块
...

# events块
events {         
   ...
}

# http块
http      
{
  # http全局块
  ...

  # 虚拟主机server块
  server {
    listen       80 default_server; # 监听HTTP端口
    listen       [::]:80 default_server;
    server_name  121.43.134.999; # 监听地址
    root         /code/dist; # 静态资源根目录

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
      # 跨域配置 start
      add_header Access-Control-Allow-Origin *;
      add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
      add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

      if ($request_method = 'OPTIONS') {
        return 204;
      }
      # 跨域配置 end
    }

    error_page 404 /404.html;
      location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
      location = /50x.html {
    }

    # gzip
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_comp_level 5;
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";

    # http全局块
    ...
}
  • 配置文件将 /code/dist 作为所有静态资源请求的根路径,如访问: http://121.43.134.999/dist/index.js,将会去 /code/dist 目录下去查找 index.js
  • 现在我们需要重启 Nginx 让新的配置生效,如:
    nginx -s reload
  • 我们在服务器 /code/dist 目录中创建或本地导入 index.html 文件之后, 就可以输入 ip 访问啦

问题

  • 配置 root 为项目文件地址后 403
    • chmod -R 777 项目文件地址
    • ps aux | grep "nginx: worker process" | awk '{print $1}' 查看用户是否一致,如果不一致 vim /etc/nginx/nginx.conf 修改第一行 user 用户保持一直,我这里都用的 root

扩展

命令 功能
nginx 启动
nginx -s stop 快速关闭
nginx -s quit 优雅的关闭 nginx 主进程会等待 worker 进程完成当前用户请求的处理
nginx -t 查看配置文件是否修改成功 (多用于配置文件修改之后)
nginx -s reopen 重新打开日志文件
nginx -s reload 重新启动
nginx -c filename 使用指定的配置文件 (default: /etc/nginx/nginx.conf)

相关文章

网友评论

      本文标题:linux 安装 nginx

      本文链接:https://www.haomeiwen.com/subject/rikbsdtx.html