不通过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]

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!