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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看