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

Avoid double redirect NGINX

· 52CE 我爱测

I'm redirecting my website users to the HTTPS version of the site using a 301 redirect with Nginx. I've tested my site using PageSpeed from Google and found that I was double redirecting from the main page. This is because of my …

问题原文

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

I'm redirecting my website users to the HTTPS version of the site using a 301 redirect with Nginx.
I've tested my site using PageSpeed from Google and found that I was double redirecting from the main page. This is because of my CMS. Example:
http:// domain.tld -> NGINX 301 -> to https:// domain.tld -> CMS redirect -> https:// domain.tld/homepage

I was hoping that I could redirect the direct root link using NGINX with

location = / {
    return 301 https:// domain.tld/homepage;
}

this works for the home page, however, this will give 404 errors to any other http page than the homepage, I tried adding return 301 https://$host$request_uri; under the location block, but somehow this overwrites the root domain rule. (which give a double redirect again) Is there any way to redirect all links with their appropriate request_uri, EXCEPT for the root domain?

P.S. I was hoping to do this without an if function: See: https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/



Here is a sample of my full config file:

server {
    listen       80;
    server_name  domainname.tld;

    location = / {
        return 301 https://domainname.tld/homepage;
    }

    return 301 https://$host$request_uri; 
    #if i remove this I'll get 404 errors on any other page than the homepage.
    #but if I add it, the 'location = /' block gets ignored.
}

server {

    listen 443 ssl;

    server_name domainname.tld;

    root /var/www/domainname.tld;
    index index.php;

    ... (stuff like rewrite rules, irrelevant) ...

}

已采纳解答

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

Just wrap it in a location / { ... } block to give it equal precedence:

server {
    listen       80;
    server_name  domainname.tld;

    location = / {
        return 301 https://$server_name/homepage;
    }
    location / {
        return 301 https://$server_name$request_uri; 
    }
}

See this document for details.

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

资料来源与适用范围

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

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

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