2014-02-25 67 views
2

堆棧溢出生成重寫URL,htaccess重寫url像堆棧溢出

所以我需要知道我能做到像堆棧溢出?

http://stackoverflow.com/questions/9168364/how-to-rewrite-seo-friendly-urls-like-stackoverflow => 200 ok.(without trailing slash) 
http://stackoverflow.com/questions/9168364/how-to-rewrite-seo-friendly-urls-like-stackoverflow/ => 200 ok.(with trailing slash) 
http://stackoverflow.com/questions/9168364/ => 301 redirect. 
http://stackoverflow.com/questions/9168364 => 301 redirect. 

我怎麼能用mod_rewrite做到這一點?

我有這樣的事情:

RewriteRule ^([0-9]+)[/]([^/]*) ./cat.php?id=$1&title=$2 [L,NC] 



mydomain.com/999 => 404 not found. 
mydomain.com/999/ => 200 ok. 
mydomain.com/999/test => 200 ok. 
mydomain.com/999/test/test2 => 200 ok. 
mydomain.com/999/test/test2/test3 => 200 ok. 
mydomain.com/999/test/test2/test3/test4 => 200 ok. 

請讓我知道我是如何改變重寫規則?

回答

4

您需要調整您的正則受了一點使得後面的斜槓可選。使用這條規則:

RewriteRule ^([0-9]+)(?:/([^/]*))?/?$ ./cat.php?id=$1&title=$2 [L,NC] 
+0

很好。正是我需要的。我可以知道我可以學習RewriteRules正則表達式嗎?有沒有這本書? – UFO

+1

對於學習mod_rewrite我相信https://askapache.com – anubhava

+0

非常好的博客@AliRaza – anubhava

1

的.htaccess:

<IfModule mod_rewrite.c> 
    Options +FollowSymLinks 
    RewriteEngine On 

    # Get rid of index.php 
    RewriteCond %{REQUEST_URI} /index\.php 
    RewriteRule (.*) index.php?rewrite=2 [L,QSA] 

    # Rewrite all directory-looking urls 
    RewriteCond %{REQUEST_URI} /$ 
    RewriteRule (.*) index.php?rewrite=1 [L,QSA] 

    # Try to route missing files 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} public\/ [OR] 
    RewriteCond %{REQUEST_FILENAME} \.(jpg|gif|png|ico|flv|htm|html|php|css|js)$ 
    RewriteRule . - [L] 

    # If the file doesn't exist, rewrite to index 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^(.*)$ index.php?rewrite=1 [L,QSA] 

</IfModule> 

的index.php:

$url = $_SERVER['REQUEST_URI']; 
$url = explode("/",substr($url,1)); 

您的鏈接將是可讀PHP如下:

http://www.website.com/First/Second/Third

$url[0] >> 'First'

$url[1] >> 'Second'

$url[2] >> 'Third'