简体   繁体   中英

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

I do not understand why this is not working for me. For url parameters, its working fine.

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.

My .htaccess as follow:

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.

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.,

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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