CKH4
CKH4

Reputation: 238

Redirect URL created with history.pushState() to base URL

I'm using javascript with history.pushState() to create a single page tab system (http://s.codepen.io/CKH4/debug/XdNoxX/). Is it possible to get a fake url created with history.pushState() and redirect it to the main page.

If my base url is 'example.com' and the fake url is 'example.com/about' I would like for any user who navigates to 'example.com/about' to be redirected to 'example.com'.

I assume there is no way to do this in plain JS (if there is though great). What would the proper way to do this?

Upvotes: 1

Views: 1164

Answers (2)

Kiran Shakya
Kiran Shakya

Reputation: 2559

Like @nemoinho said in his answer, you can achieve your objective from server side. For example, if your server supports, .htaccess rewriting rules and you are using php, then you can use following code for .htaccess file and save it in your root folder:

RewriteEngine On

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php?u=$1 [NC,QSA,L]

What above code does is, simply transfer any url segments as a parameter u to index.php, so that you can check $_GET['u'] and determine what to do, before rendering your page.

For example: https://example.com/test/rest => https://example.com/index.php?u=test/rest

Elaboration:

First line will tell server to start rewrite engine.

Second line rewrites the base as root directory. That means no matter your url is https://example.com/test/rest, it will rewrite your base as https://example.com/.

Third line is condition to check if the requested url is not actually a physical file.

Last line is executed only if third line is valid, and what it does is get every thing after base and pass that captured string as parameter to index.php in your base. [NC, QSA, L] is flag passed to rewrite rule. NC for non case sensitivity, QSA for appending other query strings too and L for skipping other rules below if it executes.

Upvotes: 1

nemoinho
nemoinho

Reputation: 614

That's not possible, but you can configure your webserver to handle all requests like they are calling the main page, e.g. by serving the same page or by a 302-redirect.

Upvotes: 1

Related Questions