Nginx rewrite练习
1、访问ip/xcz,返回400状态码,要求用rewrite匹配/xcz
a、访问/xcz返回400
b、访问/hello时正常访问xcz.html页面
server {listen 192.168.99.137:80;server_name 192.168.99.137;charset utf-8;root /var/www/html;location / {root /var/www/html;rewrite ^/xcz$ /q.html last;rewrite ^/hello$ /xcz.html last;index index.html index.htm index.php;}location = /q.html {return 400;}
}
2、访问http://kgc.com/ 时跳转至 http://jd.com
server {listen 192.168.99.137:80;server_name kgc.com;charset utf-8;root /var/www/html;location / {root /var/www/html;if ($host ~* kgc.com ) {rewrite .* http://jd.com permanent;}index index.html index.htm index.php;}}
windows hosts文件添加
192.168.99.137 kgc.com
3、访问http://kgc.com/a/1.html时跳转至http://jd.com/a/1.html
server {listen 192.168.99.137:80;server_name kgc.com;charset utf-8;root /var/www/html;location / {root /var/www/html;if ($host ~* kgc.com ) {rewrite /a/1.html http://jd.com/a/1.html permanent;}index index.html index.htm index.php;}}
4、通过http://kgc.com访问nginx根目录下的index.html
通过http://alice.kgc.com访问http://kgc.com/alice
通过http://jack.kgc.com访问http://kgc.com/jack
cd /var/www/html
mkdir jack alice
echo jack.... > jack/index.html
echo alice... > alice/index.html
windows hosts文件添加
192.168.99.137 kgc.com
192.168.99.137 jack.kgc.com
192.168.99.137 alice.kgc.com
ngnix.conf配置
server {listen 192.168.99.137:80;server_name kgc.com;charset utf-8;root /var/www/html;location / {root /var/www/html;if ($host = kgc.com ) {break;}if ( $host ~* "^(.*)\.kgc\.com$" ) {set $user $1;rewrite .* http://kgc.com/$user permanent;}}location /jack {root /usr/share/nginx/html;index index.html index.hml;}location /alice {root /usr/share/nginx/html;index index.html index.hml;}}
通过http://alice.kgc.com访问http://kgc.com/alice
访问jack.kgc.com
5、将所有URL 重定向到加上 .html 后缀的 URL,例:aa.com/a==>aa.com/a.html。
server {listen 192.168.99.137:80;server_name aa.com;charset utf-8;root /var/www/html;location / {root /var/www/html;if ($request_uri !~* "\.html$") {rewrite ^/(.*)$ /$1.html break;}}}
6、将所有 .html 结尾的 URL 重定向到去掉 .html 后缀的 URL,例:aa.com/a.html==>aa.com/a。
if ($request_uri ~* "\.html$") {rewrite ^/(.*).html$ /$1 break;}
7、将所有 /blog/post/<id>
的请求重定向到 /blog/article/<id>
,id为数字。
server {listen 192.168.0.116:80;server_name www.clean.com;charset utf-8;root /var/www/html/clean;location ~ ^/blog/post/(\d+)/$ {root /var/www/html/clean;rewrite ^/blog/post/(\d+)/$ /blog/article/$1 last;index index.html index.htm index.php;}location /article {root /var/www/html/clean/blog;index index.html index.htm index.php;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
访问192.168.0.116/post/1/