【问题标题】:Nginx re-directions from "www" to "non www" and from "http" to "https"?Nginx 从“www”重定向到“non www”以及从“http”到“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;
    }
}

那么我该怎么做呢?

【问题讨论】:

标签: nginx redirect mod-rewrite http-redirect


【解决方案1】:
  1. 只需添加一个带有server_name www.myapp.com; 的服务器块,并添加重定向:

return 301 https://myapp.com$request_uri;

  1. 将主服务器块编辑为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 的事实吗?
  • 我认为它应该这样做。
猜你喜欢
  • 1970-01-01
  • 2013-09-03
  • 2012-06-09
  • 2016-10-14
  • 2015-10-23
  • 2019-10-26
  • 2018-07-03
  • 2018-02-02
相关资源
最近更新 更多