rewrite 企业应用场景:
Nginx的rewrite功能在企业里应用非常广泛:
(1)可以调整用户浏览的URL,看起来更规范,合乎开发及产品人员的需求。
(2)为了让搜索引擎搜录网站内容及用户体验更好,企业会将动态URL地址伪装成静态地址提供服务。
(3)网址换新域名后,让旧的访问跳转到新的域名上。例如,访问京东的360buy.com会跳转到jd.com
(4)根据特殊变量、目录、客户端的信息进行URL调整等
Nginx配置rewrite过程介绍:
(1)创建rewrite语句
vi conf/vhost/www.abc.com.conf
#vi编辑虚拟主机配置文件
文件内容:
server {
listen 80;
server_name abc.com;
rewrite ^/(.*) http://www.abc.com/$1 permanent;
}
server {
listen 80;
server_name www.abc.com;
location / {
root /data/www/www;
index index.html index.htm;
}
error_log logs/error_www.abc.com.log error;
access_log logs/access_www.abc.com.log main;
}
或者
server {
listen 80;
server_name abc.com www.abc.com;
if ( $host != 'www.abc.com' ) {
rewrite ^/(.*) http://www.abc.com/$1 permanent;
}
location / {
root /data/www/www;
index index.html index.htm;
}
error_log logs/error_www.abc.com.log error;
access_log logs/access_www.abc.com.log main;
}
(2)重启服务
确认无误便可重启,操作如下:
nginx -t
#结果显示ok和success没问题便可重启
nginx -s reload
(3)查看跳转效果
打开浏览器访问abc.com
页面打开后,URL地址栏的abc.com变成了www.abc.com说明URL重写成功。