微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

nginx将所有http重定向到https,但有一个例外

我想将所有http流量重定向到https,但有一个例外.在网址中有/ preview /的任何内容我想保留在http上.

我已尝试使用以下配置,但它一直告诉我,我有一个重定向循环.

server {
    listen 80;
    server_name example.com;
    root            /var/www/html/example.com/public;
    index           index.PHP index.html;


    location /preview {
        try_files $uri $uri/ /index.PHP?$query_string;
    }

    location / {
        # we are in http server, but want https for normal
        # requests - redirect to https

        return 301 https://$server_name$request_uri;
    }


    location ~ \.PHP${
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.PHP)(/.+)$;
            # NOTE: You should have "cgi.fix_pathinfo = 0;" in PHP.ini

            # With PHP5-cgi alone:
            #fastcgi_pass 127.0.0.1:9000;
            # With PHP5-fpm:
            fastcgi_pass unix:/var/run/PHP-fpm/PHP-fpm.sock;
            fastcgi_index index.PHP;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }
}


 server {
    listen 443;
    server_name example.com;

    ssl on;
    ssl_certificate /etc/Nginx/ssl/cert_chain.crt;
    ssl_certificate_key /etc/Nginx/ssl/server.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    add_header Strict-Transport-Security max-age=31536000;

    access_log  /var/log/Nginx/example.com/access.log;
    error_log   /var/log/Nginx/example.com/error.log;

    charset utf-8;


    root            /var/www/html/example.com/public;
    index           index.PHP index.html;

    location / {
        try_files $uri $uri/ /index.PHP?$query_string;
    }

    location /preview {
        # we are in http server, but want https for normal
        # requests - redirect to https

        return 301 http://$server_name$request_uri;
    }

    location ~ \.PHP${
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.PHP)(/.+)$;
            # NOTE: You should have "cgi.fix_pathinfo = 0;" in PHP.ini

            # With PHP5-cgi alone:
            #fastcgi_pass 127.0.0.1:9000;
            # With PHP5-fpm:
            fastcgi_pass unix:/var/run/PHP-fpm/PHP-fpm.sock;
            fastcgi_index index.PHP;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }
}

解决方法:

为了确保您在任何情况下都不会在/ preview中发布任何重定向,您可能希望始终使重定向成为有条件的,例如:

listen 80;
location / {
    if ($request_uri !~ /preview) {
        return 302 https://...;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐