大网数据广告活动
网站运营与故障问答

nginx: 301 redirect to non-www, SSL urls on default_server(s)

· 52CE 我爱测

My goal is to have nginx primarily return a check for all requested URLs that start with http:// and/or contain //www. , and 301 redirect them to the URL where //www. is replaced by // and http:// replaced by https:// . In short,…

问题原文

原帖链接 · marko-36 · CC BY-SA 4.0

My goal is to have nginx primarily return a check for all requested URLs that start with http:// and/or contain //www., and 301 redirect them to the URL where //www. is replaced by // and http:// replaced by https://.

In short, all requests, if necessary, to be redirected to their non-www, SSL version, so that subsequently, all other non-default servers, serving as reverse-proxies for specific domains, will then always get https, non-www requests.

How do I do this?

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

The http server does not require a specific certificate, so all domains can be redirected to https non-www with a single server block.

For example:

server {
    listen 80;
    server_name ~^(www\.)?(?<domain>.+)$;
    return 301 https://$domain$request_uri;
}

See this document for more.


The https servers probably require a specific certificate for each domain. To redirect from www to non-www, a specific certificate should be valid for both name variants. You should use two server blocks for each specific domain, the existing one and another to perform the redirect.

For example:

server {
    listen 443 ssl;
    server_name www.example.com;

    ssl_certificate     /path/to/example.com.crt;
    ssl_certificate_key /path/to/example.com.key;

    return 301 https://example.com$request_uri;
}
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /path/to/example.com.crt;
    ssl_certificate_key /path/to/example.com.key;

    ... this is the existing server block for this domain ...
}

See this document for more.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2018-11-14)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。