Nginx - 通用将所有 www 重定向到非 www [英] Nginx - Generic redirect all www to non-www

查看:53
本文介绍了Nginx - 通用将所有 www 重定向到非 www的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Nginx 中创建一个通用的 HTTP -> HTTPS 和 WWW -> 非 WWW 重定向,这会影响所有域.还是我需要为每个域都设置它?

Is it possible to make a generic HTTP -> HTTPS and WWW -> non-WWW redirect in Nginx which impact all domains. Or do I need to set it up for every single domain?

我已将 HTTP->HTTPS 设为如下:

I've made the HTTP->HTTPS as follows:

server {
    listen 80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}

推荐答案

为此您应该使用两个服务器块:

You should use two server blocks for this:

server { # redirect http/https www.example.com to https://example.com
    listen 80;
    listen 443 ssl;
    server_name www.example.com;
    ssl_certificate     <path_to_ssl_cert_for_domain_www.example.com>;
    ssl_certificate_key <path_to_key_for_ssl_cert_above>;
    # other ssl parameters here if needed
    return 301 https://example.com$request_uri;
}

server { # redirect http://example.com to https://example.com
    listen 80;
    server_name example.com;
    return 301 https://example.com$request_uri;
}

server { # main site config
    listen 443 ssl;
    server_name example.com;
    # rest of your configuration here
    ...
}

通常付费的 SSL 证书已经包含带 www 前缀和不带 www 前缀的域名.如果您使用 Lets Encrypt 服务,您可以自己为 example.comwww.example.com 生成证书.

Usually paid SSL certificates already includes both domain name with www prefix and without it. If you're using Lets Encrypt service, you can generate certificate for both example.com and www.example.com by yourself.

这篇关于Nginx - 通用将所有 www 重定向到非 www的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆