Nginx 从“www”重定向到“non www”以及从“http”到“https”?
Posted
技术标签:
【中文标题】Nginx 从“www”重定向到“non www”以及从“http”到“https”?【英文标题】:Nginx re-directions from "www" to "non www" and from "http" to "https"? 【发布时间】:2020-10-01 06:16:30 【问题描述】:我的应用托管在基本 URL 中:https://myapp.com/
现在我想添加从“www”到“non www”/“http”到“https”的重定向,其中:
https://myapp.com/
https://www.myapp.com/
http://myapp.com/
http://www.myapp.com/
最后 3 个 URL 应该 301 重定向到第一个。
现在第二个 URL 没有被重定向,最后 2 个使用 307 重定向而不是 301 重定向。
这是我的 nginx 配置:
server
listen 80;
server_name myapp.com www.myapp.com;
location /
return 301 https://$host$request_uri;
server
listen 443 ssl;
server_name myapp.com www.myapp.com;
server_tokens off;
ssl_certificate /etc/nginx/conf.d/self-signed-fullchain.pem;
ssl_certificate_key /etc/nginx/conf.d/self-signed-privkey.pem;
include /etc/nginx/conf.d/options-ssl-nginx.conf;
ssl_dhparam /etc/nginx/conf.d/ssl-dhparams.pem;
location /
root /usr/share/nginx/html;
index index.html index.htm;
location ~ ^/(api)/
proxy_pass http://myapp:3000;
那么我该怎么做呢?
【问题讨论】:
见this 答案。 【参考方案1】:-
只需添加一个带有
server_name www.myapp.com;
的服务器块,并添加重定向:
return 301 https://myapp.com$request_uri;
-
将主服务器块编辑为
server_name myapp.com;
应该是这样的:
server
listen 80;
server_name myapp.com www.myapp.com;
location /
return 301 https://$host$request_uri;
server
listen 443 ssl;
server_name www.myapp.com;
server_tokens off;
ssl_certificate /etc/nginx/conf.d/self-signed-fullchain.pem;
ssl_certificate_key /etc/nginx/conf.d/self-signed-privkey.pem;
include /etc/nginx/conf.d/options-ssl-nginx.conf;
ssl_dhparam /etc/nginx/conf.d/ssl-dhparams.pem;
return 301 https://myapp.com$request_uri;
server
listen 443 ssl;
server_name myapp.com;
server_tokens off;
ssl_certificate /etc/nginx/conf.d/self-signed-fullchain.pem;
ssl_certificate_key /etc/nginx/conf.d/self-signed-privkey.pem;
include /etc/nginx/conf.d/options-ssl-nginx.conf;
ssl_dhparam /etc/nginx/conf.d/ssl-dhparams.pem;
location /
root /usr/share/nginx/html;
index index.html index.htm;
location ~ ^/(api)/
proxy_pass http://myapp:3000;
【讨论】:
这会解决目前“http”到“https”使用 307 重定向而不是 301 的事实吗? 我认为它应该这样做。以上是关于Nginx 从“www”重定向到“non www”以及从“http”到“https”?的主要内容,如果未能解决你的问题,请参考以下文章
nginx 本地重定向从 /var/www/html/index.html 到 /var/www/html/larvel_project/public
NGINX 将 http 重定向到 https,将非 www 重定向到 ww