Nginx从 "www "重定向到 "non www",从 "http "重定向到 "https"?

问题描述 投票:0回答:1

我把我的应用程序托管在基本的URL中,现在我想把 "www "到 "non www "的重定向添加到 "http "到 "https"。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个URL是用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个回答
0
投票
  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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.