Nginx 301 永久跳转和 URL 重写(用于域名更换和 http 跳转 https)

# 域名 301 永久跳转 (www to none-www or non-www to www),亦可单独用于一条 server{} 字段。
# 配置文件默认位于 [root@hexingxing conf.d]# pwd
# /etc/nginx/conf.d
server {
    listen 80;
    server_name www.domain.com;
    # $scheme will get the http protocol
    # and 301 is best practice for tablet, phone, desktop and seo
    return 301 $scheme://domain.com$request_uri;
}
# 域名 https URL 重写 (http2https)
# 配置文件默认位于 [root@hexingxing conf.d]# pwd
# /etc/nginx/conf.d
server {
    listen       80;
    # listen       80 default_server;
    # listen       [::]:80 default_server;
    server_name  domanin.com;
    root         /tmp/sev;
    rewrite ^(.*)$  https://$host$1 permanent;
    ...
}
# 域名 https URL if 方式重写 (Redirect non-https traffic to https)
# 配置文件默认位于 [root@hexingxing conf.d]# pwd
# /etc/nginx/conf.d
server {
    if ($host = baidu.com) {
        return 301 https://$host$request_uri;
    }
}
# 域名 https URL if 方式重写 (Redirect non-https traffic to https)
# 配置文件默认位于 [root@hexingxing conf.d]# pwd
# /etc/nginx/conf.d
server {
	# Redirect non-https traffic to https
	if ($scheme != "https") {
	    return 301 https://$host$request_uri;
	} 
}

1 条评论

昵称
  1. Pingback: HTTPS 时代,使用 Certbot (Let’s Encrypt) – 何小湘