首页 >后端开发 >php教程 >Nginx 在 https 端口上强制 http 转为 https

Nginx 在 https 端口上强制 http 转为 https

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-11-10 05:27:02860浏览

Nginx force http to https On  https Port

示例脚本 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

以上是Nginx 在 https 端口上强制 http 转为 https的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn