duan_2000 2013-07-18 12:43
浏览 52
已采纳

不通过ajax请求URL时的PHP重定向(在wordpress页面上时)

I have a Wordpress website with Domain: Hello.com which is "ajaxified". what I want to know is how to redirect user back to Hello.com if they visit Hello.com/ask, Hello.com/cake or anything deeper using the browser address bar.

Even if they go 2 degrees deeper like Hello.com/cake/make, I want them to stay at the root of my website.

I am using Wordpress and my first Idea was to put redirect script at header, but ended up making an infinite redirect loop.

How can I redirect users to homepage without redirecting my ajax requests to the homepage as well?

[If you ask why I would disallow them to go deeper, the answer is: I am using ajax to load deeper pages and everything else into a div]

  • 写回答

1条回答 默认 最新

  • duanlachu7344 2013-07-18 15:16
    关注

    By adding a short PHP script somewhere before everything else, I was able to check how my pages were loaded using the condition below.

    if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
    

    It allowed me to check through PHP if it was through Ajax or not.

    The value of $_SERVER['HTTP_X_REQUESTED_WITH'] is xmlhttprequest when the request was an ajax request.

    For my case, this is how I used it:

    if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        header("Location: http://". $_SERVER['HTTP_HOST']."/");
    }
    

    Which would check if the request was done through ajax, and redirect to the homepage/Main Screen of the website/web App if not.

    I got the idea after reading this post


    Note: Usage of HTTP_X_REQUESTED_WITH depends on the JavaScript framework you are using, if it sets that header. I am using jQuery and it does it for you. Also $_SERVER is not entirely a part of PHP so it also depends if your server passes that variable to PHP. If you are on a Nginx Server and it doesn't work for you, you can try this: Passing HTTP_X_REQUESTED_WITH from nginx to php

    Hope this helps others!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算