如何在 nginx 上强制显式 `http://example.com` 为 https

问题描述 投票:0回答:1

如何在 nginx 上强制

http://example.com
https://example.com

这是我当前的配置,仅当输入

example.com
时才有效,它会按照预期重定向到 https,但如果我使用显式方案 http
http://example.com
键入,则不会重定向到 https。

server {
  listen 80 default_server;
  listen [::]:80 default_server ipv6only=on;

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

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    ssl_certificate     /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    ...

}
nginx nginx-config
1个回答
0
投票

示例脚本 nginx :

server 
{

        listen 443 default ssl;
        listen [::]:443 ssl;
        root /var/www/html/api_mobile/public;

        include snippets/ssl-params.conf;

        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-Content-Type-Options "nosniff";
        index index.html index.php index.htm index.nginx-debian.html;

        server_name sitename.com;

        charset utf-8;
        location / {
             if ($scheme ="http") {
                # redirect all non api traffic to https block
                return 301 https://$server_name$request_uri;
             }           

            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; }


        error_page 404 /index.php;
        location ~ \.php$ {
            fastcgi_pass unix:/run/php/php8.2-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            include fastcgi_params;
        }

    ssl_certificate /etc/letsencrypt/live/sites/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/site/privkey.pem; # managed by Certbot
}

关于计划条件:

if ($scheme ="http") 
{
                # redirect all non api traffic to https block
                return 301 https://$server_name$request_uri;
}   

它在一个端口 443 https 上重定向的核心强制 http 到 https

© www.soinside.com 2019 - 2024. All rights reserved.