Node.js Nginx 配置之:如何从 http 定向到 https,从没有 www 定向到 www?
需求
最近给一个网站上了 https,需求如下:
- 所有没有 www 的链接跳转到 www 开头的;
- 所有 http 链接跳到加密 https 链接。
解决方案
直接贴代码。
server {
listen 80;
server_name www.abc.com abc.com;
return 301 https://www.abc.com$request_uri;
}
server {
listen 443 ssl;
server_name www.abc.com abc.com;
root /www/wwwroot/abc.com/www;
set $node_port 9999;
if ($host != 'www.abc.com' ) {
rewrite ^/(.*)$ https://www.abc.com/$1 permanent;
}
#SSL-START SSL相关配置,请勿删除或修改下一行带注释的404规则
ssl_certificate /www/server/cert/1_abc.com_bundle.crt;
ssl_certificate_key /www/server/cert/2_abc.com.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #按照这个协议配置
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;#按照这个套件配置
ssl_prefer_server_ciphers on;
#SSL-END
index index.js index.html index.htm;
if ( -f $request_filename/index.html ){
rewrite (.*) $1/index.html break;
}
if ( !-f $request_filename ){
rewrite (.*) /index.js;
}
location = /index.js {
proxy_http_version 1.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://127.0.0.1:$node_port$request_uri;
proxy_redirect off;
}
#禁止访问的文件或目录
location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md) {
return 404;
}
#一键申请SSL证书验证目录相关设置
location ~ \.well-known {
allow all;
}
location ~ /static/ {
etag on;
expires max;
}
}