如果要实现这个功能首先需要启用Rewrite 模块
要使用重定向的功能的话首先得先启动 Apache 的 mod_rewrite 模块,然后重启 Apache 服务
1 2 | a2enmod rewrite service apache restart[或者service httpd restart] |
启用了 Rewrite 模块后就可以愉快的使用 .htaccess 文件来设置 Rewrite 规则了
进入Apache 配置文件,在原有配置文件基础上加入下列代码
1 2 3 4 | Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all |
如果是Lnmp需要修改Directory路径为 一键包默认的网站目录,其中 /var/www/html 换成你的实际路径,也就是你在配置文件中设置的 DocumentRoot。
保存并重启 Apache 服务~
1 | service apache restart[或者service httpd restart] |
配置 Rewrite 模块
切换到文档根目录,创建一个 .htaccess 文件,然后用 Vim 之类的编辑器打开
1 2 3 | cd /var/www/html touch .htaccess vim .htaccess |
或者本地新建个.htaccess文件上传到你的网站目录中
如果要让所有访问带 www 的都重定向到不带 www 的,则往 .htaccess 文件中写入
1 2 3 4 | RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] |
如果要让所有访问不带 www 的都重定向到带 www 的,则改成
1 2 3 4 | RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] |
重启 Apache 服务
1 | service apache restart[或者service httpd restart] |
同样的,如果你使用的是 https 服务器,则只需要将上述的 Rewrite 规则中的 http 改成 https 即可。
使用 curl 命令测试一下重定向是否生效
1 | curl -I http://example.com |
假设我们是把所有不带 www 的都重定向到带 www 了,则返回的结果应该类似于
1 2 3 4 5 6 7 | HTTP/1.1 301 Moved Permanently Server: nginx/1.6.2 Date: Tue, 16 Jun 2015 09:36:09 GMT Content-Type: text/html Content-Length: 193 Connection: keep-alive Location: http://www.example.com/ |
重点的是 301 Moved Permanently 以及下方的 Location。