Nginx重定向到SSL,但特定URL除外



我想将所有到我的网站的流量重定向到SSL,除了单个URL方案。我希望这个单一的方案返回一个响应,表明该网站的这一特定部分只能直接通过SSL使用。

我的站点的conf文件目前部分看起来像这样,它可以很好地重定向所有流量:

server {
    listen 80;
    server_name sub.example.com;
    rewrite ^ https://$server_name$request_uri? permanent;
}
server {
    listen 443;
    ssl on;
    ssl_certificate /etc/nginx/ssl/12345.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
    server_name sub.example.com;
    client_max_body_size 4G;
    # ....
}

我想这样做:

  • http://sub.example.com->https://sub.example.com
  • http://sub.example.com/someallowedurl->https://sub.example.com/someallowedurl
  • http://sub.example.com/api->不允许。你必须去https://sub.example.com/api直接
  • http://sub.example.com/api/something->不允许

将服务器级别的重写移动到根位置,然后为API生成错误代码,为该状态代码设置错误页面,并将您的人类可读描述放在那里。假设你返回403,这似乎是合适的,然后湿得到这个:

root /path/to/webroot;
location / {
    return 301 https://$host$request_uri;
}
location /api/ {
    error_page 403 /api_direct.html;
    deny all;
}

我已经设置了根,以便可以找到自定义错误页面,根据您的需要进行调整。

最新更新