简体   繁体   English

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

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

I want to redirect to a custom URL if my visitors use any of the URL such as index.php?permalink=query or if trailing slash is missing on the REQUEST_URI 如果访问者使用任何URL(例如index.php?permalink=queryREQUEST_URI缺少斜杠,我想重定向到自定义URL

I do not understand why this is not working for me. 我不明白为什么这对我不起作用。 For url parameters, its working fine. 对于url参数,其工作正常。

What am I doing wrong with the following code? 以下代码在做什么?

    $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;
    }

It is redirecting when a query comes as index.php?permalink=$query where as when if URL does not contain trailing slash then its not redirecting. 当查询以index.php?permalink=$query query出现时,它正在重定向,就像URL不包含尾部斜杠表示不重定向一样。

My .htaccess as follow: 我的.htaccess如下:

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

I cannot force all URLs to have trailing slash using .htaccess as some of the important URLs does not contain trailing slash. 我不能使用.htaccess强制所有URL都带有斜杠,因为某些重要的URL不包含斜杠。

EDIT 编辑

Though now using the following in .htaccess works, but it adds trailing slash to css or js or font files such as otf / ttf / woff etc., 虽然现在可以在.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]

I want to redirect to a custom URL if my visitors use any of the URL such as index.php?permalink=query or if trailing slash is missing on the REQUEST_URI 如果访问者使用任何URL(例如index.php?permalink=queryREQUEST_URI缺少斜杠,我想重定向到自定义URL

You can use the following rule to accomplish this : 您可以使用以下规则来完成此操作:

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