如何让nginx对一个位置要求HTTPS,而对所有其他位置要求HTTPS是可选的?

如何让nginx对一个位置要求HTTPS,而对所有其他位置要求HTTPS是可选的?,http,https,nginx,Http,Https,Nginx,目前,我使用两个listen指令为nginx配置了一个同时提供HTTP和HTTPS服务的站点: listen 80 default_server; listen 443 ssl; 我想将此配置用于站点内的所有位置;但是,我只希望在某个位置需要HTTPS location / { // Both HTTP and HTTPS } location /admin { // Require HTTPS } 我该怎么做呢?是否需要单独的HTTP和HTTPS服务器配置?我将它们拆分为两台服务

目前,我使用两个
listen
指令为nginx配置了一个同时提供HTTP和HTTPS服务的站点:

listen 80 default_server;
listen 443 ssl;
我想将此配置用于站点内的所有位置;但是,我只希望在某个位置需要HTTPS

location / {
  // Both HTTP and HTTPS
}

location /admin {
  // Require HTTPS
}

我该怎么做呢?是否需要单独的HTTP和HTTPS服务器配置?

我将它们拆分为两台服务器

server {
    listen 80;
    server_name example.com www.example.com;

    location / {
        #normal config
    }

    location /admin {
        return 301 https://$http_host$request_uri;
    }
}

server {
    listen 443 ssl;
    server_name example.com www.example.com;

    location / {
        #normal config for frontend
    }

    location /admin {
        #admin settings
    }
}
您可以将公共配置拆分为一个单独的文件,并将其包含在两个服务器中,而不是每次更改任何内容时都重写这两个文件