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

Have nginx redirect everything to https except one directory

· 52CE 我爱测

I need nginx to redirect all http URLs to https, with the exception a ".secret/" directory which should continue to be served as http. So, for example: http://example.com/a.html --> https://example.com/a.html http://example.org/z…

问题原文

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

I need nginx to redirect all http URLs to https, with the exception a ".secret/" directory which should continue to be served as http.

So, for example:

  • http://example.com/a.html --> https://example.com/a.html
  • http://example.org/z/b.html --> https://example.org/z/b.html
  • http://example.com/.secret/x.html --> http://example.com/.secret/x.html

I have the following in my configuration but for http, it returns addresses that include "_".

server {
    listen 80;
 
    server_name _;
 
    location /.secret {
        return http://$server_name$request_uri;
    }
 
    location / {
        return 301 https://$server_name$request_uri;
    }
}

What am I doing wrong?

UPDATE:

Combining the comments from @mforsetti and @Pothi_Kalimuthu, the following worked:

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

已采纳解答

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

it returns addresses that include "_".

server_name _;

location /.secret {
   return http://$server_name$request_uri;
}

$server_name returns assigned server_name to the server block, which in your case is _; hence the _ in returned address.

If you want it to return a hostname or your Host request header, try using $host, something like:

location /.secret {
    return http://$host$request_uri;
}

.secret/ directory which should continue to be served as http

if you want to serve a directory, specify a root directory.

location /.secret {
    root /path/to/your/parent/of/secret/directory;
}

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

资料来源与适用范围

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

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

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