url rewrite是服務器的一個模塊,功能包括,配置一些訪問的網址的重寫,其中的語句規則是基於正則表達式.
其中涉及到的變量都是基於服務器上(apache或者nginx)通用的變量,具體一些變量詳細解釋以及nginx下rewrite的一些配置實例請參考ngnix的rewrite參數,用法。
比如爲了使網址更加友好,可以將用戶看到的網址www.simple.com/ming-tian-shi-ge-hao-tian-qi.html重定位到www.simple.com/ming/tian/shi/ge/hao/tian/qi.html,這樣用戶看到的就是一個網址而不是一個個的文件夾。
其他還有很多有用的功能,比如,防止別的網站引用你網站的圖片,如果別人使用的是你網站的圖片的話,那麼佔用的是你的網站的流量,但是卻不能給你帶來訪問量
還比如可以自己寫一個友好的404頁面,如果發生404錯誤的時候就將頁面定位到自己寫的404頁面。
還可以將css文件還有js文件設置保存在用戶瀏覽器上面的時間,加快網頁的加載速度。
下面是nginx上面的rewrite配置文件
1 server {
2 listen 80;
3 server_name www.simple.com ;
4 root /home/www/simple;
5 index index.php index.html index.htm;
6 charset utf-8;
7 access_log logs/simple.access.log main;
8 #如果請求主機字段不等於'www.simple.com'則重定向到http://www.simple.com/*
9 if ( $host != 'www.simple.com' ) {
10 rewrite ^/(.*)$ http://www.simple.com/$1 permanent;
11 }
12 #如果當前請求的文件路徑不存在,將出現/tool/的網址重定向到/tool/index.php,將出現kisswall/的網址重定向到/kisswall/index.php
13 if ( !-e $request_filename ) {
14 rewrite ^(.*)tool/(.*)$ $1tool/index.php last;
15 rewrite ^(.*)kisswall/(.*)$ $1kisswall/index.php last;
16 }
17 location / {
18 directio 1;
19 output_buffers 1 128k;
20 index index.php index.html index.htm ;
21 rewrite ^(.*?)-(.*)$ $1.php?$2;
22 }
23 #指定404錯誤頁面
24 error_page 404 /404.html;
25 location = /50x.html {
26 }
27 #設置js、css過期時間
28 location ~ \.(css|js)$ {
29 expires 1w;
30 }
31 #防盜鏈
32 location ~ \.(jpg|jpeg|png|gif|swf|ico)$ {
33 valid_referers none bloacked *.erqilu.com *.renren.com *.weibo.com;
34 if ( $invalid_referer ) {
35 return 404;
36 }
37 expires max;
38 }
39 location ~ \.php$ {
40 fastcgi_pass 127.0.0.1:9000;
41 fastcgi_index index.php;
42 fastcgi_param SCRIPT_FILENAME /$document_root$fastcgi_script_name;
43 include fastcgi_params;
44 }
45 #禁止htaccess
46 location ~ /\.ht {
47 deny all;
48 }
49 #將出現/min/的網址定位到/min/index.php?*
50 location /min/{
51 rewrite /min/([a-z]=.*) /min/index.php?$1 last;
52 #expires 1w;
53 }
54 }
apache對應的.htaccess文件如果訪問的網址不是“localhost”或者“127.0.0.1”則跳轉到http:
//localhost/
|
對照可參考apache和nginx配置的異同,
其中nginx的url rewrite配置文件存放的位置是:usr/local/nginx/conf