nginx:重定向从http到https的所有内容,除了一个url-pattern

时间:2015-01-09 09:24:35

标签: nginx

我有一个只能通过HTTPS访问的网站,除了一个网址模式(因为我在某些网页上有http-iframe&s;我想避免安全警告)

E.g. this pages should be redirected to https:
http://example.com
http://example.com/a/this-is-an-article
http://example.com/v/this-is-a-video

This pages should not be redirected to https (or should be redirected form https to http)
http://example.com/l/page-with-unsafe-iframe
http://example.com/l/other-page-with-unsafe-iframe

3 个答案:

答案 0 :(得分:52)

如果iframe页面始终位于同一目录中,则可以使用简单的前缀位置。

server {
    listen 443;

    location /l/ {  # redirect https iframe requests to http server
        return 301 http://$server_name$request_uri;
    }
    # ...
}

server {
    listen 80;

    location / {  # the default location redirects to https
        return 301 https://$server_name$request_uri;
    }

    location /l/ {}  # do not redirect requests for iframe location
    # ...
}

答案 1 :(得分:14)

您可以使用地图和简单的重定向规则,例如:

map $uri $redirect_https {
    /l/page-with-unsafe-iframe         0;
    /l/other-page-with-unsafe-iframe   0; # you can use regex here
    default                            1;
}

server {
    listen 443;

    if ($redirect_https = 0) {
       return 301 http://$server_name$request_uri;
    }

    # other code
}
server {
    listen 80;

    if ($redirect_https = 1) {
       return 301 https://$server_name$request_uri;
    }

    # other code
}

我应该提一下,301重定向是一种很好的做法,不像永久重写。

答案 2 :(得分:0)

对于php入口点文件,您也可以这样尝试:

if($_SERVER['DOCUMENT_ROOT'] && ((!isset($_SERVER['HTTPS']) || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'http'))) {
   header('HTTP/1.1 301 Moved Permanently');
   header('Location: '.'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
   exit;
}