×

Nginx

Nginx:域名及单页面301重定向设置方法

litang litang 发表于2014-05-29 23:36:06 浏览216 评论0

抢沙发发表评论

日常工作中使用301重定向的情况很多:如网页目录结构变动,网页重命名、网页的扩展名改变、网站域名改变、SEO优化、等等,301重定向可以很方便的使页面实现跳转。 一、首先更改配置文件

[root@slave logs]# cat ../conf/vhosts/test.com.conf               #test.com.conf 配置文件
server    
{
        listen       80;
        server_name  test.com www.test.com;                       #服务器的基本名称,多域名用空格隔开
        root   /data/web;                                       
        access_log  logs/test.com.access.log;                    
        
        if ($host != 'www.test.com')                                         #if指令 用于条件判断
        {
        rewrite ^/(.*) http://www.test.com/$1 permanent;          #注意这里 访问test.com 301重定向到 www.test.com
        }
 
        #rewrite ^/bbs/(.*) http://bbs.test.com/$1 permanent;      #此处注释将在下面使用      

        location / 
        {
            index  index.html index.htm index.php;
        }

        error_page 500 502 503 504 /50x.html;
        location =/50x.html
        {
            root html;
        }

        location ~* \.php$
        {
            root /data/web;
            fastcgi_pass  127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME  /data/web$fastcgi_script_name;
            include       fastcgi_params;
        }
} 单页面301重定向: 把http://example.com/tags.php?para=xxx 重定向到 http://example.com/tags 若按照默认的写法:rewrite ^/tags.php(.*) /tags permanent; 重定向后的结果是:http://example.com/tags?para=xxx 如果改写成:rewrite ^/tags.php(.*) /tags? permanent; 那结果就是:http://example.com/tags 所以,关键点就在于“?”这个尾缀。假如又想保留某个特定的参数,那又该如何呢?可以利用Nginx本身就带有的$arg_PARAMETER参数来实现。 例如: 把http://example.com/tags.php?para=xxx&p=xx 重写向到 http://example.com/tags?p=xx 可以写成:rewrite ^/tags.php /tags?p=$arg_p? permanent; 只求结果的朋友可以直接忽略前面的内容,看这里: rewrite ^/tags.php /tags permanent; //重写向带参数的地址 rewrite ^/tags.php /tags? permanent; //重定向后不带参数 rewrite ^/tags.php /tags?id=$arg_id? permanent; //重定向后带指定的参数