【问题标题】:htaccess rewrite url like Stack Overflowhtaccess 重写 url 像 Stack Overflow
【发布时间】:2014-02-25 10:56:00
【问题描述】:

Stack Overflow 生成重写 URL,

所以我需要知道如何像 Stack Overflow 一样做到这一点?

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.

请告诉我如何更改 RewriteRule ?

【问题讨论】:

    标签: php regex apache .htaccess mod-rewrite


    【解决方案1】:

    您需要通过使尾部斜杠可选来稍微调整您的正则表达式。使用这条规则:

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

    【讨论】:

    • 太棒了。正是我需要的。我可以知道如何学习 RewriteRules 正则表达式吗?有这方面的书吗?
    • @anubhava 我正在做类似RewriteRule ^([0-9]+)\/?$ index.php?id=$1&title=$2 [NC] 的事情,但它不起作用。仅显示帖子 ID。我是否需要使用标题作为 GET 参数以及 id 来搜索数据库才能使其正常工作?
    • @maxxon15:使用RewriteRule ^([0-9]+)(?:/([^/]*))?/?$ index.php?id=$1&title=$2 [L,QSA],如果没有解决,请打开一个新问题。
    • 重写器工作得很好,但是我现在失去了从 url 使用 $_GET['id] 的能力,就像@maxxon15 所问的那样......有什么解决方案吗?
    • @anubhava 我们开始:stackoverflow.com/questions/71610284/…
    【解决方案2】:

    .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] &gt;&gt; 'First'

    $url[1] &gt;&gt; 'Second'

    $url[2] &gt;&gt; 'Third'

    【讨论】:

      猜你喜欢
      • 2014-04-07
      • 2011-02-14
      • 2010-11-05
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 2011-03-19
      • 2022-01-18
      相关资源
      最近更新 更多