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

nginx将所有http重定向到https,只有一个例外,nginx,Nginx,我想将所有http流量重定向到https,但有一个例外。url中有/preview/的任何内容我都希望保留在http上 我尝试了下面的配置,但它一直告诉我我有一个重定向循环 server { listen 80; server_name example.com; root /var/www/html/example.com/public; index index.php index.html; location

我想将所有http流量重定向到https,但有一个例外。url中有/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://...;
    }
}

您不能在混合HTTP/HTTPS上使用HST。您可以向我提供有关此问题的任何文档吗@Tanhongtat服务普通HTTP请求有什么意义?你真的想通过HTTP公开身份验证的cookies吗?非常感谢。它现在运转良好。我会更新,如果有任何问题。