下列配置后:
http://111.111.111.111:8001/test (可以访问)
https://111.111.111.111:8001/test (不能访问,https的访问需要域名)
https://111.111.111.111/test (不能访问,80端口的访问需要用域名)
https://xxx.com.cn/test (可以访问,标准)
http://xxx.com.cn/test (可以访问,http转为https)
1.监听443端口
worker_processes 1;
events {
worker_connections 1024;
}
http{
server {
listen 80;
server_name xxx.com;
#访问80端口时,把http的域名请求转成https 统一变成get方式的请求
rewrite ^(.*)$ https://$host$1 permanent;
}
#配置ssl证书
#https通过443端口监听
server {
listen 443 ssl;
ssl_certificate C:/Users/xxx/Desktop/nginx-1.18.0/SSL/Nginx/server.crt; # 刚生成的crt
ssl_certificate_key C:/Users/xxx/Desktop/nginx-1.18.0/SSL/Nginx/server.key; # 刚生成的key
server_name xxx.com; # 你的域名
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
location / {
proxy_pass http://127.0.0.1:8001; # 本地服务器地址及端口
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Forward-Proto https;
proxy_http_version 1.1;
# for websocket
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
}
2.监听非443端口
这里需要注意消息头的Host这一项需要加上端口号 $ host:$ server_port。
同时我这里折腾了很久,原因是每次修改配置文件后用命令 nginx -s reload 没有报错,我将进程杀死重启后才发现端口被占用了,nginx无法启动
#https通过34249端口监听
server {
listen 35249 ssl;
ssl_certificate /usr/local/nginx/conf/ssl/7116817_www.xx.com.cn.pem; #需要将cert-file-name.pem替换成已上传的证书文件的名称。
ssl_certificate_key /usr/local/nginx/conf/ssl/7116817_www.xx.com.cn.key; #需要将cert-file-name.key替换成已上传的证书私钥文件的名称。
server_name xx.com.cn; #需要将yourdomain.com替换成证书绑定的域名
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
location / {
proxy_pass http://localhost:35259; # 本地服务器地址及端口
# 非默认端口需要添加$server_por(重点)
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 X-Forwarded-Proto $scheme;
}
}