LNMP中域名301重定向的方法

处于SEO考虑,经常要301重定向,比如把没有www的定向到www的域名。在LNMP中进行301重定向其实也很简单。

下面演示一下将域名eincy.com重定向到www.eincy.com的方法:
1.打开/usr/local/nginx/conf/vhost目录下相应的.conf文件,比如我的是/usr/local/nginx/conf/vhost/www.eincy.com.conf

里面的原来应该是

server
{
listen 80;
server_name www.eincy.com eincy.com;
index index.html index.htm index.php default.html default.htm default.php;
root /home/wwwroot; include none.conf;
location ~ .*\.(php|php5)?$
{
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fcgi.conf;
} location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
} location ~ .*\.(js|css)?$
{
expires 12h;
} access_log off;
}

如果上面代码的server_name后面同时存在www.eincy.com eincy.com两个域名,就把eincy.com这个删除了。
2.在后面加上

server {
server_name eincy.com;
rewrite ^(.*)$ https://ilovetile.sijie.wang$1 permanent;
}

3.现在的总代码应该是

server
{
listen 80;
server_name www.eincy.com;
index index.html index.htm index.php default.html default.htm default.php;
root /home/wwwroot; include none.conf;
location ~ .*\.(php|php5)?$
{
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fcgi.conf;
} location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
} location ~ .*\.(js|css)?$
{
expires 12h;
} access_log off;
}
server {
server_name eincy.com;
rewrite ^(.*)$ https://ilovetile.sijie.wang$1 permanent;
}

4.重启LNMP

/root/lnmp stop
/root/lnmp start

现在,用eincy.com域名访问就会自动跳转到www.eincy.com啦。



12 thoughts on “LNMP中域名301重定向的方法

  1. Apache 的话,直接修改 .htaccess 更简单;

    rewriteEngine on
    rewriteCond %{http_host} ^eincy.com[NC]
    rewriteRule ^(.*)$ http://www.eincy.com/$1 [R=301,L]

    不过,应该将www重定向为无w的,这样 URL 更简洁;

Comments are closed.