【问题标题】:Delete ugly ?pg=1 from URL via .htacess RewriteRule通过 .htaccess RewriteRule 从 URL 中删除所有 ?page=1
【发布时间】:2011-01-05 01:09:31
【问题描述】:

我的 CMS 中有分页插件,它会生成 ?pg=1 链接。我想在没有这个丑陋的后缀的情况下重定向这个 url,因为没有它 CMS 也会显示第一页。

所以,我有像 http://site.ru/category/schock-crane/?pg=1http://site.ru/moyka/?type=granit&pg=1 这样的网址 我想将这些网址分别重定向到http://site.ru/category/schock-crane/http://site.ru/moyka/?type=granit

我试过这个 .htaccess 代码

RewriteRule (.*)(&|\?)pg=1$ $1 [R=301,L]

我在正则表达式培训师那里尝试了这个正则表达式代码 - 它有效。但在实时服务器上不会发生重定向。

这是整个 .htaccess 文件:

AddDefaultCharset Off
#DirectoryIndex index.php index.html

Options +FollowSymLinks
Options -Indexes

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # fix /?pg=1
    RewriteRule (.*)(&|\?)pg=1$ $1 [R=301,L]

    # fix .palitra-tab
    RewriteCond %{REQUEST_URI} -tab$
    RewriteRule (.*)/([0-9]*)/\.(.*)-tab?$ http://site.ru/redirect.php?id=$2 [R=301,L]

    RewriteCond %{REQUEST_URI} ^/csss/.* [NC]
    RewriteRule csss/(.*)\.css$ css.php?n=$1 [L]

    #RewriteRule ^(.*)/csss/(.*) /test.php [L]

    RewriteRule ^(.*)/base([0-9]+)/?$ $1?base=$2 

    #RewriteCond %{REQUEST_FILENAME} -f
    #RewriteRule \.(gif|jpeg|jpg|png)$ /images/watermark/index.php [L]

    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.+) - [PT,L]

    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^(.*) index.php

    RewriteCond %{HTTP:Authorization}  !^$
    RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
</IfModule>

【问题讨论】:

  • 远程服务器上是否启用了mod_rewrite?如果删除 &lt;IfModule mod_rewrite.c&gt; 条件会发生什么?
  • mod_rewrite 有效 - CMS 成功使用 clean-url

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


【解决方案1】:

您需要使用RewriteCond 来检查查询字符串:

RewriteCond %{QUERY_STRING} ^(([^&]*&)*)pg=1(&(.*)|$)
RewriteCond %1%4 (.*?)&?$
RewriteRule ^ %{REQUEST_URI}?%1 [R=301,L]

第二个RewriteCond 只是删除一个尾随&amp;

【讨论】:

  • 不起作用 - 没有发生 url 重定向。没有你的例子的第二行试过 - 也没有成功。你能在你的服务器上测试一下吗?
  • @the_ghost:我已经对其进行了测试,它适用于测试用例?pg=1?&amp;pg=1?pg=1&amp;?foo&amp;pg=1?pg=1&amp;foo。只需确保将此规则放在那些仅进行内部重写的规则之前。
【解决方案2】:

也许缺少的^/ 会终止重定向

# fix /?pg=1
RewriteRule ^(.*)(&|\?)pg=1$ /$1 [R=301,L]

或者试试

RewriteRule ^(.*)(&|\?)pg=1$ http://%{HTTP_HOST}/$1 [R=301,L]

【讨论】:

    猜你喜欢
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多