今天一個客戶聯(lián)系我他的馬來西亞vps 怎么設(shè)置301重定向,我要了資料一看,竟然安裝的是LNMP,是個牛人,于是我也是百度,到處亂找,終于找到了,接下來我就把方法步驟整理一下,LNMP下的Nginx如果想將域名lnmp.org 301重定向到www.lnmp.org,同時www.lnmp.org已經(jīng)添加上,可以按如下步驟修改 使用命令編輯器vi、nano或winscp圖形管理軟件編輯對應(yīng)的虛擬主機(jī),一般虛擬主機(jī)配置文件位于:/usr/local/nginx/conf/vhost/域名.conf ,如添加的域名是www.lnmp.org則配置文件是/usr/local/nginx/conf/vhost/www.lnmp.org.conf 在配置文件代碼如下:
lnmp.org 301跳轉(zhuǎn)到www.lnmp.org示例配置如下:
省略www.lnmp.org虛擬主機(jī)server配置 server {
listen 80;
server_name lnmp.org;
return 301 http://www.lnmp.org$request_uri;
}
如果是想讓http強(qiáng)制跳轉(zhuǎn)到https,把里面的http換成https就行。
http站點(diǎn)301跳轉(zhuǎn)到https站點(diǎn)示例配置如下:
server {
listen 443 ssl;
server_name www.lnmp.org;
省略其他配置
} server {
listen 80;
server_name lnmp.org;
return 301 https://www.lnmp.org$request_uri;
}
按上面例子修改完成后保存,執(zhí)行:/etc/init.d/nginx restart 重啟nginx,使其生效。
該設(shè)置不適用于Let'sEncrypt及其他需要http驗證的SSL證書;如果使用DNS API方式可以使用這種設(shè)置方法。
如果是想讓https://lnmp.org強(qiáng)制跳轉(zhuǎn)到https://www.lnmp.org
可以在https的虛擬主機(jī)配置文件中root行或server_name行下面添加上
if ($host = 'lnmp.org') { return 301 https://www.lnmp.org$request_uri; }
如果要設(shè)置對應(yīng)域名的http跳到對應(yīng)https站點(diǎn)上
如:http://lnmp.org 跳到 https://lnmp.org,http://www.lnmp.org 跳到 https://www.lnmp.org 上。
在對應(yīng)域名的http虛擬主機(jī)配置文件中添加:return 301 https://$host$request_uri;
如果使用Let'sEncrypt免費(fèi)SSL證書
使用的Let's Encrypt的免費(fèi)證書且使用http驗證方式生成的SSL證書,如果你要想設(shè)置301,編輯要設(shè)置301域名的nginx虛擬主機(jī)配置文件,找到包含有l(wèi)isten 80;的server段,在
location ~ /.well-known { allow all; }
這幾行下面添加,如下配置:
location / { return 301 https://$host$request_uri; }
保存,如果不設(shè)置會導(dǎo)致證書無法正常續(xù)期。
完整的適用于Let'sEncrypt的301跳轉(zhuǎn)配置文件如下:
server { listen 80; #listen [::]:80; server_name lnmp.org www.lnmp.org; index index.html index.htm index.php default.html default.htm default.php; root /home/wwwroot/lnmp.org; location ~ /.well-known { allow all; } location / { return 301 https://$host$request_uri; } }
注意:以上所有更改nginx的配置都需要重啟ngin生效。