【问题标题】:convert original URL to friendly URL via mod-rewrite通过 mod-rewrite 将原始 URL 转换为友好 URL
【发布时间】:2016-08-19 22:02:15
【问题描述】:

我的页面中有 2 种类型的 url。

1-http://www.example.com/index.php?id=12

我一直想要这个:

http://www.example.com/12

但对于其他类似的东西:

2-http://www.example.com/index.php?id=12&id2=123&asd=qwe&svd=sdf...

我想要它没有改变:

http://www.example.com/?id=12&id2=123&asd=qwe&svd=sdf...

所以我只想重定向http://www.example.com/index.php?id=12

我试试这个

RewriteCond %{THE_REQUEST} ^GET\ /(.*/)?(?:index\.php)?\?id=([^\s&]+) [NC]
RewriteRule ^ /%1%2? [R=301,L]

它只适用于第一个 (http://www.example.com/index.php?id=12)

但第二次,它重定向到 (http://www.example.com/***)

我在stackoveflow中阅读我必须使用[QSA,L]

所以我试试这个:

RewriteCond %{THE_REQUEST} ^GET\ /(.*/)?(?:index\.php)?\?id=([^\s&]+) [NC]
RewriteRule ^ /%1%2? [QSA,L]

但我收到 500 错误(内部服务器错误)

这是我的完整代码:

RewriteEngine On
RewriteBase /



RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]


RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{THE_REQUEST} ^GET\ /(.*/)?(?:index\.php)?\?id=([^\s&]+) [NC]
RewriteRule ^ /%1%2? [R=301,L]

---编辑---

我可以这样做

RewriteRule ^index.php/([^/]+)/?([^/]*) /index.php?id=$1 [NC]

例如 www.example.com/123 有效!

但 www.example.com/index.php?id=123 不会重定向到 www.example.com/12

【问题讨论】:

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


    【解决方案1】:

    要将http://example.com/index.php?id=foo 转换为http://example.com/foo,您可以在root/.htaccesso 中使用以下规则:

    RewriteEngine on
    
    #1)Redirect "/index.php?id=foo" to "/foo"#
    RewriteCond %{THE_REQUEST} /(?:index\.php)?\?id=([^\s&]+)\sHTTP [NC]
    RewriteRule ^ /%1? [L,R]
    #2)The rule bellow will internally map "/foo" to "/index.php?id=foo"#
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/?$ /index.php?id=$1 [L]
    

    [已测试] 这适用于我的 apache 服务器。

    【讨论】:

    • 谢谢。但 'id2=123&asd=qwe&svd=sdf' 就是一个例子。每个名称和值都可以来这里...对于 id=12 , 12 也不是固定的。它可以是每个数字或字符。
    • 或者你可以修复你的最后一条规则以匹配特定的url RewriteCond %{THE_REQUEST} ^GET\ /(.*/)?(?:index\.php)?\?id=([^\s&]+)\sHTTP [NC] RewriteRule ^ /%1%2? [QSA,L]
    • 谢谢,但我只想重定向 www.example.com/?id=123 格式,而不是其他格式……QSA 也返回给我一个内部服务器错误
    • QSA 不返回服务器错误,您需要使用 R 标志而不是 QSA,因为您想从查询字符串重定向到干净的 url
    猜你喜欢
    • 2012-07-27
    • 2011-09-23
    • 2019-04-30
    • 1970-01-01
    • 2018-09-20
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多