nginx-禁用特定URL的HTTPS重定向

时间:2019-03-26 00:32:46

标签: nginx

我有nginx设置,可以将所有HTTP请求重定向到HTTPS,就像这样:

# Redirect every request to HTTPS...
server {
    listen 80;
    listen [::]:80;

    server_name .sub.example.com;
    return 301 https://$host$request_uri;
}

我要求不强制将特定路由发送到HTTPS /iot/{token}/weather

我试图像这样更新nginx配置:

# Redirect every request to HTTPS...
server {
    listen 80;
    listen [::]:80;

    location ~* ^/iot/[0-9a-z]/weather$ {
        break;
    }

    server_name .sub.example.com;
    return 301 https://$host$request_uri;
}

但是HTTP请求仍然被强制使用HTTPS。

所以我尝试这样做:

# Redirect every request to HTTPS...
server {
    listen 80;
    listen [::]:80;

    server_name .sub.example.com;

    location ~* ^/iot/[0-9a-z]/weather$ {
        break;
    }

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

但是,这仍然行不通。

以上是在下面的前一节中导入的唯一文件:

# FORGE CONFIG (DO NOT REMOVE!)
include forge-conf/sub.example.com/before/*;

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name sub.example.com;
    root /home/forge/sub.example.com/public;

    # FORGE SSL (DO NOT REMOVE!)
    ssl_certificate /etc/nginx/ssl/sub.example.com/467330/server.crt;
    ssl_certificate_key /etc/nginx/ssl/sub.example.com/467330/server.key;

    ssl_protocols TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/nginx/dhparams.pem;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    # FORGE CONFIG (DO NOT REMOVE!)
    include forge-conf/sub.example.com/server/*;

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

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/sub.example.com-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

# FORGE CONFIG (DO NOT REMOVE!)
include forge-conf/sub.example.com/after/*;

我会很乐于帮助您进行设置,以便我可以指定一个不应该重定向到HTTPS的匹配URL,然后将所有其他URL重定向到HTTPS。

1 个答案:

答案 0 :(得分:0)

尝试:

server {
    listen 443;

    location / {  
        return 301 http://$server_name$request_uri;

    }

}

server {
    listen 80;

    location /iot/ {  
        return 301 http://$server_name$request_uri;

    }

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

}

应该是2个文件,一个用于http端口80,另一个用于443。