大网数据广告活动
服务器运维问答

nginx redirect to www.domain

· 52CE 我爱测

I want to redirect the site ALWAYS to www.site.com. However, I am not sure as to how to get the WWW to always show up in front should say someone type in the domain without the www. EDIT: server { listen 80; server_name site.com;…

问题原文

原帖链接 · Jake Thomas · CC BY-SA 3.0

I want to redirect the site ALWAYS to www.site.com. However, I am not sure as to how to get the WWW to always show up in front should say someone type in the domain without the www.

EDIT:

server {
        listen  80;
        server_name  site.com;
        rewrite ^(.*) https://www.site.com$1 permanent;
}

server {
    listen       80;
    server_name  www.site.com;
    #rewrite ^(.*) https://www.site.com$1 permanent;
    root /home/site/public_html;

        listen       443 ssl;

If I type in site.com it goes to https://www.site.com = SUCCESS

If I type in site.com/index.php it goes to http://www.site.com = NO SSL

Ideas?

社区高分解答

原帖链接 · moestly · CC BY-SA 4.0

It's better to use return instead of rewrite, because it's faster.

server {
    listen 80;
    server_name     example.com;
    return          301 http://www.example.com$request_uri;
}

server {
    listen 80;
    server_name     www.example.com;
    [...]
}

This way, we also send the client a proper status code, so that he asks the right domain in the next request.

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

资料来源与适用范围

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

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

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