繁体   English   中英

如果缺少斜杠或使用参数,则PHP重定向到自定义URL

[英]PHP Redirecting to Custom URL if trailing slash is absent or with parameters

如果访问者使用任何URL(例如index.php?permalink=queryREQUEST_URI缺少斜杠,我想重定向到自定义URL

我不明白为什么这对我不起作用。 对于url参数,其工作正常。

以下代码在做什么?

    $requesturl = $_SERVER['REQUEST_URI'];

    if($requesturl == "/index.php?permalink=".$query || substr($requesturl, -1) != '/') {
        $redirect_requesturl = $baseurl."/".$query."/";
        Header( 'HTTP/1.1 301 Moved Permanently' );
        Header( 'Location: ' . $redirect_requesturl );exit;
    }

当查询以index.php?permalink=$query query出现时,它正在重定向,就像URL不包含尾部斜杠表示不重定向一样。

我的.htaccess如下:

RewriteEngine On
RewriteBase /
RewriteRule ^([^/.]+)?/$ index.php?permalink=$1&%{QUERY_STRING}

我不能使用.htaccess强制所有URL都带有斜杠,因为某些重要的URL不包含斜杠。

编辑

虽然现在可以在.htaccess中使用以下代码,但是它会在css或js或otf / ttf / woff等字体文件中添加斜杠,

RewriteCond %{REQUEST_URI}  !\.(php|html?|jpg|gif|png|jpeg|pdf|doc|docx|css|js|xml|xls|xsl|txt|ico|eot|svg|ttf|woff|woff2|otf|flv|swf)$
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]

如果访问者使用任何URL(例如index.php?permalink=queryREQUEST_URI缺少斜杠,我想重定向到自定义URL

您可以使用以下规则来完成此操作:

RewriteEngine on

# if the requested uri has querystring
RewriteCond %{QUERY_STRING} ^permalink=.+$ [OR]
# or the trailing slash is missing
RewriteCond %{REQUEST_URI} !/$
# redirect the request to /custom_url 
RewriteRule ^(.+)$ /custom_url? [L,R]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM