dsjgk330337 2016-07-02 14:59
浏览 152

如果缺少尾部斜杠或带参数,PHP重定向到自定义URL

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]
  • 写回答

1条回答 默认 最新

  • doulian4762 2016-07-02 15:31
    关注

    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]
    
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?