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

Redirect http to https for certain path on an Nginx site

· 52CE 我爱测

How do you redirect certain paths on an Nginx-hosted site from http to https? I want to ensure everyone visiting the path "/admin" is behind https. Googling finds me several guides about how to add global rewrite rules, but I can…

问题原文

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

How do you redirect certain paths on an Nginx-hosted site from http to https?

I want to ensure everyone visiting the path "/admin" is behind https. Googling finds me several guides about how to add global rewrite rules, but I can't find anything about how to add a rewrite rule for a specific site.

All the examples I see for doing this use the server{} syntax, which isn't allowed in a site's configuration file. What's the site-specific syntax equivalent?

I have a load balancer that accepts 443 connections, does all the SSL handling, and forwards requests to my server on port 80, do Nginx doesn't actually need to serve requests on port 443. It just needs to see that requests are originally coming from http and redirect the user to https. Previously, I was doing this redirect in Apache using a rewrite rule like:

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

What's the equivalent in Nginx?

已采纳解答

原帖链接 · Pothi Kalimuthu · CC BY-SA 4.0

The equivalent configuration in Nginx is...

if ( $x-forwarded-proto != 'https' ) return https://$host$request_uri; }

Please be aware that "using if is not evil" if used correctly.

How do you redirect certain paths on an Nginx-hosted site from http to https?

location /pathtoredirect { return https://$host$request_uri; }

So, for your particular situation, the solution would go something like this...

location /admin {
  if ( $x-forwarded-proto != 'https' )
    return https://$host$request_uri;
  }

  # directives to process /admin when accessed via https
  # ...
  # ...
}

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

资料来源与适用范围

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

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

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