【问题标题】:Redirect URL for client and Rewrite for server with mod_rewrite使用 mod_rewrite 为客户端重定向 URL 并为服务器重写
【发布时间】:2012-08-18 11:26:45
【问题描述】:

我有以下问题,已经解决了几十次,但我没有找到任何解决方案。

我正在编写一个博客引擎,希望拥有漂亮的 URL,因此我在 .htaccess 中使用 Apache mod_rewrite/page/3 => /?s=3 之类的东西工作得很好,因为我可以在 PHP 脚本中编写漂亮的 URL。但是我有一个使用method="get" 进行搜索的表单字段来提交,所以除了将客户端指向丑陋的 URL 之外我别无选择。所以我想要的是一种Redirect 客户端然后Rewrite 服务器的URL:/?q=foo =client=> /search/foo =server=> /?q=foo。 (还有/?q=foo&s=2 => /search/2/foo

不知怎的,我的规则不起作用,我希望你能帮助我。

RewriteRule ^(index\.php)?\?q=(.*)$ search/$2 [R,L]
RewriteRule ^(index\.php)?\?q=(.*)&s=(.*)$ search/$3/$2 [R,L]

RewriteRule ^search/(\d+)/(.*)/?$ index.php?q=$2&s=$1 [NC,L]
RewriteRule ^search/([^/]*)/?$ index.php?q=$1 [NC,L]

【问题讨论】:

    标签: .htaccess mod-rewrite redirect url-rewriting


    【解决方案1】:

    只有当实际请求是针对丑陋的 URL 时才需要重定向,您无法匹配 URI,因为它会循环:请求丑陋的 URL,重定向到友好的 URL,请求友好的 URL,重写为丑陋的 URI在内部,重定向到友好的 URL 等

    所以试试这个,而不是你的两条规则:

    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(index.php)?\?q=([^&]+)&s=([^\ ]+)
    RewriteRule ^ /search/%3/%2/? [L,R=301]
    
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(index.php)?\?q=([^\ &]+)
    RewriteRule ^ /search/%2/? [L,R=301]
    

    【讨论】:

    • 对不起,但这对我没有用,我现在得到了 500 :( 我的 error.log 告诉我:[Sat Aug 18 05:18:42 2012] [alert] [client 127.0.0.1] .../.htaccess: RewriteCond: cannot compile regular expression '^[A-Z]{3,9}\\ /(index.php)?\\?q=([^\\ &]+)\\', referer: http://localhost/.../?q=foo 我什至尝试修改你的代码,但没有任何效果。
    • @Ps0ke 对不起,第二个重写条件中有一个类型,最后有一个杂散的``,我已经编辑了答案
    • 还是不行。没有错误了,但它仍然没有重定向。 RewriteCond 中的第一个字符串是什么(^[A-Z]{3,9}`) and why is the regex in the RewriteRule` 只是一个 ^-Start-Of-Line 标记?
    • @ps0ke 因为%{THE _REQUEST} 看起来像这样:GET /?q=something HTTP/1.1 及其与最需要的方法(GET)的匹配。第二件事 os 因为我们不关心 uri 是什么,我们只是在条件中匹配它。
    • 那么我们不应该使用 %{REQUEST_URI} 吗? "REQUEST_URI 请求的 URI 的路径组件,例如 /index.html。这特别不包括可作为其自己的名为 QUERY_STRING 的变量的查询字符串。"
    猜你喜欢
    • 2020-07-02
    • 2011-04-14
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多