侧边栏壁纸
博主头像
SHO酱的Blog博主等级

行动起来,活在当下

  • 累计撰写 109 篇文章
  • 累计创建 148 个标签
  • 累计收到 3 条评论

目 录CONTENT

文章目录

Nginx 安装 & 配置记录

SHO酱
2021-12-29 / 0 评论 / 0 点赞 / 599 阅读 / 3051 字

在 CentOS 中 Nginx 安装步骤

安装必要的工具

gcc安装

yum -y install gcc-c++

pcre安装

yum  -y install  pcre pcre-devel

zlib安装

yum -y install zlib zlib-devel

OpenSSL安装

yum -y install openssl openssl-devel

安装 Nginx

获取 Nginx 源码

配置

进入源码目录,使用如下命令在编译前进行配置

./configure \
--user=nginx --group=nginx \          #安装的用户组
--prefix=/usr/local/nginx \           #指定安装路径
--with-http_stub_status_module \         #监控nginx状态,需在nginx.conf配置
--with-http_ssl_module \             #支持HTTPS
--with-http_sub_module \             #支持URL重定向
--with-http_gzip_static_module          #静态压缩

编译、安装

make && make install

反向代理配置

location /{
    proxy_pass http://localhost:8080;
    proxy_set_header Host $host:$server_port;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

在反向代理时将客户端真实IP

location /{
    ... ...
    proxy_set_header Host $host;#保留代理之前的host
    proxy_set_header X-Real-IP $remote_addr;#保留代理之前的真实客户端ip
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header HTTP_X_FORWARDED_FOR $remote_addr;#在多级代理的情况下,记录每次代理之前的客户端真实ip
    proxy_set_header X-Forwarded-Proto $scheme; #表示客户端真实的协议(http还是https)
    proxy_redirect default;#指定修改被代理服务器返回的响应头中的location头域跟refresh头域数值
}

静态路径引用 root 和 alias

location / {
    alias  /root/server/ruoyi/web/;
#            root   html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
}

解决 Vue 页面刷新被重定向

location / {
    ... ...
    try_files $uri $uri/ /index.html;
}

单独配置API接口域名后,前端请求报 403 错误

由于单独给 API 配置域名api.xxx.xx,Vue前端使用默认域名www.xxx.xx,实际发生了跨域请求,导致 403 错误。

这里需要添加配置,允许跨域请求服务,OPTIONS握手请求返回204,不再阻碍POST继续请求

location / {
    ... ...
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers '*';
    if ($request_method = 'OPTIONS') {
        return 204;
    }
}

参考

Centos7.3安装nginx
【Nginx实战】Nginx设置允许跨域请求 解决OPTIONS 403错误

0

评论区