|
Nginx 配置重定向
为了实现 301 重定向,需要在原有的配置文件里多添加一段代码,比如这是我原来的 Nginx 配置文件
[ol]server { listen 80; listen [::]:80; root /var/www/html; server_name www.example.com example.com; index index.html index.htm index.php; location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php5-fpm.sock; }}[/ol]复制代码
我现在要让所有访问带 www 的都重定向到不带 www 的,则需要改成这样
[ol]server { listen 80; server_name www.example.com; return 301 $scheme://example.com$request_uri;}server { listen 80; root /var/www/html; server_name www.example.com example.com; index index.html index.htm index.php; location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php5-fpm.sock; }}[/ol]复制代码
如果要让所有访问不带 www 的都重定向到带 www 也是依葫芦画瓢
[ol]server { listen 80; server_name example.com; return 301 $scheme://www.example.com$request_uri;}server { listen 80; root /var/www/html; server_name www.example.com example.com; index index.html index.htm; location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php5-fpm.sock; }}[/ol]复制代码
最后不要忘了重新加载一下 Nginx 的配置文件或者重启一下 Nginx 服务
nginx -s reload 或者 service nginx restart
注意:如果是 https 服务器,则将 80 端口改成 443 即可。

Apache 配置重定向
启用 Rewrite 模块
要使用重定向的功能的话首先得先启动 Apache 的 mod_rewrite 模块,然后重启 Apache 服务
[ol]a2enmod rewriteservice apache2 restart[/ol]复制代码
启用了 Rewrite 模块后就可以愉快的使用 .htaccess 文件来设置 Rewrite 规则了,使用过 WordPress 之类的 CMS 系统的朋友们是不是很眼熟呢?
启用 .htaccess 文件
打开 Apache 的配置文件,在原有配置文件基础上加入
[ol] Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all[/ol]复制代码
其中 /var/www/html 换成你的实际路径,也就是你在配置文件中设置的 DocumentRoot。
保存并重启 Apache 服务~
service apache2 restart
配置 Rewrite 模块
切换到文档根目录,创建一个 .htaccess 文件,然后用 Vim 之类的编辑器打开
[ol]cd /var/www/htmltouch .htaccessvim .htaccess[/ol]复制代码
如果要让所有访问带 www 的都重定向到不带 www 的,则往 .htaccess 文件中写入
[ol]RewriteEngine OnRewriteBase /RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]RewriteRule ^(.*)$ http://%1/$1 [R=301,L]``` 如果要让所有访问不带 www 的都重定向到带 www 的,则改成``` bashRewriteEngine OnRewriteBase /RewriteCond %{HTTP_HOST} !^www\. [NC]RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L][/ol]复制代码
最后重启一下 Apache 服务就可以了
service apache2 restart
同样的,如果你使用的是 https 服务器,则只需要将上述的 Rewrite 规则中的 http 改成 https 即可。
测试
使用 curl 命令测试一下重定向是否生效
[ol]curl -I http://example.com[/ol]复制代码
假设我们是把所有不带 www 的都重定向到带 www 了,则返回的结果应该类似于
[ol]HTTP/1.1 301 Moved PermanentlyServer: nginx/1.6.2Date: Tue, 16 Jun 2015 09:36:09 GMTContent-Type: text/htmlContent-Length: 193Connection: keep-aliveLocation: http://www.example.com/[/ol]复制代码
重点的是 301 Moved Permanently 以及下方的 Location。 |
|