Nginx全局301永久重定向 - yumao233/MCSManager-v8.7 GitHub Wiki

通过配置网站的 Nginx 配置文件,可以做到基于 http 协议头或者基于端口号的301重定向(一般用于https跳转)
以下是两种跳转的写法(仅限于Nginx)

http协议头形式  
if ($scheme = http ) {return 301 https://$host:这里填要跳转到的端口$request_uri;}  
  
端口形式  
if ($server_port = 80 ) {return 301 https://$host:这里填要跳转的端口$request_uri;}  

一般来说,内网用户想要让面板支持 HTTPS 的话,可以使用基于协议头形式的跳转

nginx网站配置示例(宝塔Nginx配置文件示例):
第九行为301基于http协议跳转的规则写法
访问 http://域名:776 自动跳转到 https://域名:777

server
{
    listen 776;
	listen 777 ssl http2;
    server_name mcsm.suwings.top;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/mcsm.suwings.top;
    
    if ($scheme = http ) {return 301 https://$host:777$request_uri;}
    
    #SSL-START SSL相关配置,请勿删除或修改下一行带注释的404规则
    #error_page 404/404.html;
    ssl_certificate    /www/server/panel/vhost/cert/mcsm.suwings.top/fullchain.pem;
    ssl_certificate_key    /www/server/panel/vhost/cert/mcsm.suwings.top/privkey.pem;
    ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    error_page 497  https://$host$request_uri;

    #SSL-END
    
    #ERROR-PAGE-START  错误页配置,可以注释、删除或修改
    #error_page 404 /404.html;
    #error_page 502 /502.html;
    #ERROR-PAGE-END
    
    #PHP-INFO-START  PHP引用配置,可以注释或修改
    #清理缓存规则

    location ~ /purge(/.*) {
        proxy_cache_purge cache_one $host$1$is_args$args;
        #access_log  /www/wwwlogs/mcsm.suwings.top_purge_cache.log;
    }
	#引用反向代理规则,注释后配置的反向代理将无效
	include /www/server/panel/vhost/nginx/proxy/mcsm.suwings.top/*.conf;

	include enable-php-00.conf;
    #PHP-INFO-END
    
    #REWRITE-START URL重写规则引用,修改后将导致面板设置的伪静态规则失效
    include /www/server/panel/vhost/rewrite/mcsm.suwings.top.conf;
    #REWRITE-END
    
    #禁止访问的文件或目录
    location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
    {
        return 404;
    }
    
    #一键申请SSL证书验证目录相关设置
    location ~ \.well-known{
        allow all;
    }
    
    access_log  /www/wwwlogs/mcsm.suwings.top.log;
    error_log  /www/wwwlogs/mcsm.suwings.top.log;
}