Nginx配置笔记

Nginx配置笔记

hash070 396 2022-04-10

Nginx 反向代理后端口消失问题

原因是宝塔自动生成的Nginx反向代理配置文件会重写URL而且不带端口号
自动生成的代码:

#PROXY-START/
location  ~* \.(gif|png|jpg|css|js|woff|woff2)$
{
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header REMOTE-HOST $remote_addr;
    expires 12h;
}
location /
{
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header REMOTE-HOST $remote_addr;

    add_header X-Cache $upstream_cache_status;

    #Set Nginx Cache

        add_header Cache-Control no-cache;
}

#PROXY-END/

解决方法:在proxy_set_header Host那一行加上端口号,修改后的代码如下所示

#PROXY-START/
location  ~* \.(gif|png|jpg|css|js|woff|woff2)$
{
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header REMOTE-HOST $remote_addr;
    expires 12h;
}
location /
{
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header REMOTE-HOST $remote_addr;

    add_header X-Cache $upstream_cache_status;

    #Set Nginx Cache

        add_header Cache-Control no-cache;
}

#PROXY-END/

宝塔Nginx用IP+端口号配置网站,并部署SSL证书后,直接用https访问会报错

原因:宝塔部署SSL证书后,只设置了443使用HTTPS协议,而自己设定的端口没有声明为SSL协议,直接用https协议去访问一个非https协议的端口肯定会出现错误。
示例:我想在这个IP的8089端口创建一个HTTPS协议的网站,宝塔自动生成代码如下:

    listen 80;
    listen 443 ssl http2;
    listen 8089;
    server_name bt.com 172.21.1.117;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/bt.com;

可以看到8089是一个不支持ssl的普通http端口,这时直接用https访问这个端口肯定是行不通的。解决方案也很简单,把需要设定为HTTPS的端口加个SSL声明就行了,修改后的代码如下:

    listen 8089 ssl http2;
    server_name bt.com 172.21.1.117;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/bt.com;