首页 > 解决方案 > PHP 当重写页面 urls 如何删除或重定向 category.php?cat_id=2 urls 到重写的 urls?

问题描述

我正在使用此URL 重写和 PHP文件夹结构来重写 URL。我完成了它工作正常,但是在重写 URL 之后,好的,现在我有两个 URL,一个是简单的 URL /~admin/product-category.php?cat_id=2,第二个重写 URL /~admin/product-category/men-items,那么如何将第一个 URL 重定向到第二个 URL?或者只是第一个 URL 不应该因为重复的内容问题而工作。

我的项目链接:

第一个链接: http: //199.192.21.232/~admin/product-category.php ? cat_id=2 重写链接:http: //199.192.21.232/~admin/product-category/men-items

脚本

define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/' );

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/product-category/(?'product_category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'
);

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        include( INCLUDE_DIR . $action . '.php' );
        exit();
    }
}

include( INCLUDE_DIR . '404.php' );

.htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

标签: phpredirecturl-rewriting

解决方案


在您的 htaccess 顶部,放置以下规则:

RewriteEngine on

RewriteCond %{QUERY_STRING} ^cat_id=2$ [NC]
RewriteRule category.php$ http://199.192.21.232/~admin/product-category/men-items? [L,R=302]

这将重定向http://199.192.21.232/~admin/product-category.php?cat_id=2http://199.192.21.232/~admin/product-category/men-items.

如果您有多个具有相同 queryString 的旧 URL,只需将条件模式从 更改^cat_id=2$^cat_id=.+$。当您确定重定向工作正常时,更改R=302R=301使重定向永久。


推荐阅读