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

https:// redirect to https://www in NGINX

· 52CE 我爱测

How do you redirect all non-www links to my website to https://www. I know that there are a lot of solutions for .htaccess but I haven't been able to find anything sufficient for nginx. At the moment all I have is ## # Redirect n…

问题原文

原帖链接 · Recap · CC BY-SA 3.0

How do you redirect all non-www links to my website to https://www. I know that there are a lot of solutions for .htaccess but I haven't been able to find anything sufficient for nginx.

At the moment all I have is

##
# Redirect non-www to www
##
server {
     listen 80;
     server_name example.com; # add other domains separated by a space as necessary
     rewrite ^/(.*)$ https://www.example.com/$1 permanent;
}

which redirects:

example.com
www.example.com
http://example.com
http://www.example.com

to https://www.example.com which is what I want, except that https://example.com doesn't redirect https://www.example.com

How do so how do I get https:// to redirect to https://www.?

已采纳解答

原帖链接 · Recap · CC BY-SA 3.0

Since my last answer using the "if" statement is not recommended in most cases, I came up with another solution which seems to be working perfectly.

What I did was create another server block with www in the server_name and had my other server blocks redirect to it.

server {
    listen 80;
    listen [::]:80 default_server ipv6only=on;
    return 301 https://www.example.com$request_uri;
}

# HTTPS — proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com;
    return 301 https://www.example.com$request_uri;

    # Use the Let’s Encrypt certificates
    ...
}

server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name www.example.com;

    # Use the Let’s Encrypt certificates
    ...
}

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

资料来源与适用范围

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

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

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