Nginx的使用

以下命令的前提是配置了环境

# 开启
nginx
# 重新加载
nginx -s reload
# 关闭 (stop强制)
nginx -s stop
nginx -s quit
# 检查配置
nginx -t

基本配置

worker_processes  1;

events {
    worker_connections  1024;
}

upstream webp {
    server 127.0.0.1:3333;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        location / {
            proxy_pass http://webp;  
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

进阶

有些功能的使用需要安装新模块

负载均衡

没实践过

upstream guwenjie_http {
        server **.***.***.***:9503 weight=1;
        server **.***.***.***:8811 weight=2;
}

文件限制

这里有大坑,必须把nginx完全重启生效

client_max_body_size 100m;

缓存

需要经常修改的地方不建议开启,谁用谁知道

# 静态压缩
gzip_static on; 
# 配置缓存
add_header Cache-Control public,max-age=60,s-maxage=60; 

HTTPS

关于网站不安全 购买ssl证书 阿里云每年有20个证书 2022年 下载文件解压得到两个文件 xxx.pem和xxx.key

# 80端口跳转433
rewrite ^(.*)$ https://$host$1 permanent;
#xxx.pem所在的绝对路径
ssl_certificate      /xxx/xxx/xxx.pem;
#xxx.pem所在的绝对路径
ssl_certificate_key  /xxx/xxx/xxx.key;

详细配置

设置多台服务器要注意 通过二级域名跳转到本地另外一个服务器需要在末尾加/ proxy_pass http://time/;


    upstream time {
     server 127.0.0.1:8080;
    }

    upstream blog {
     server 127.0.0.1:8090;
    }

    upstream webp {
     server 127.0.0.1:3333;
    }

    server {
        listen       80;
        server_name  codeui.top;    
        rewrite ^(.*)$ https://$host$1 permanent;
    }

    # HTTPS server
    server {
       listen       443 ssl;
       server_name  codeui.top;

       ssl_certificate      xxx.pem	
       ssl_certificate_key  xxx.key


       ssl_ciphers  HIGH:!aNULL:!MD5;
       ssl_prefer_server_ciphers  on;

        location /upload/ {
        proxy_pass http://webp;  
        proxy_set_header X-Real-IP $remote_addr;
        proxy_hide_header X-Powered-By;
        proxy_set_header HOST $http_host;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        }

        location /time/ {
            proxy_pass     http://time/;
            proxy_set_header  Host       $host;
            proxy_set_header  X-Real-IP    $remote_addr;
            proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        }
 
        location / {
            gzip_static on; # 静态压缩
            # add_header Cache-Control public,max-age=60,s-maxage=60; # 配置缓存
            proxy_set_header HOST $host;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass     http://blog;
        }
    }

}