Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My page runs on php for no js-users. For users with javascript on I load all content dynamic fromt the index in combination with the hashchangevent. So the links all look like www.page.com/#page.php, with a # before it. If the user types it in that way every thing works like charm and the content is being loaded over the index.php

But if a user would enter www.page.com/page.php the page of course ends up on the php page and the dynamic page will of course not work any more except the user will hit the index page and go on navigate from that. So that's not a cool way.

My Question:

How can I redirect user from:

www.page.com/page.php

to

www.page.com/#page.php

when they typed in www.page.com/page.php in the Browser

Of course only with javascript. The Page should work without javascript on normally with php.

Thank you.

share|improve this question
What if someone with JavaScript enabled wants to share the page they're on with a friend who doesn't have JavaScript enabled? – icktoofay Sep 18 '11 at 22:49
add comment (requires an account with 50 reputation)

1 Answer

up vote 0 down vote accepted

When the page loads, change the window.location to the desired URL by deconstructing and reassembling the URI. Unfortunately, you'll have to include this on every page (i.e., page.php) on which you'd like the redirect to happen.

$(document).ready(function () {
    // Insert the pathname after the hash, but skip the leading '`'
    window.location = "/#" + document.location.pathname.slice(1);
});

It's slightly less clean, but you could also remove the window.location bit from .ready() entirely. This would effect an small performance improvement.

If you want the hash-redirect to affect only the last element of the current path, use the code below, instead.

window.location = "./#" + document.location.pathname.split('/').pop();
share|improve this answer
Very cool! Thanks! But what if my URL is longer, f.e. www.page.com/folder/page.php - or even more folder. What would I have to change? Cause now this moves the # to www.page.de/#folder/page.php. – Melros Sep 18 '11 at 22:58
Nothing. The Location.pathname property captures everything that comes after the domain name and before the query string. – cheeken Sep 18 '11 at 23:00
Yes, that's why www.page.com/folder/#page.php won't work? – Melros Sep 18 '11 at 23:06
I am not certain I understand your question, but please see my amended answer as it may have the solution. – cheeken Sep 18 '11 at 23:15
PERFECT!! That's exactly what I needed! Thank you so much!! – Melros Sep 18 '11 at 23:20
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.