Javascript cannot find mod_rewrite query string!

I use the following javascript class to pull variables from a query string:

getUrlVars : function() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars; } 

So it works : http://example.com/signinup.html?opt=login

I need to http://www.example.com/login/ work the same. Using mod_rewrite:

RewriteRule ^login/? signinup.html?opt=login [QSA]

allows you to load a page, load javascript, load css, but my javascript functions cannot find the opt key (i.e. it is undefined ). How do I get opt in javascript?

+6
javascript regex apache mod-rewrite
source share
5 answers

Javascript is client-side. Mod_rewrite is server-side.

Therefore, Javascript will never see the rewritten URL. For your browser, the URL you entered is the final address.

The only real solution is to change your Javascript so that it looks at the URL it received, and not the old version (or perhaps parsed both alternatives, as the old URL will still work, and people may still have the old ones bookmarks).

Another possible solution would be to go to your server code (PHP? Whatever?), Where you can see the rewritten URL and insert some javascript code there that you can parse on the client side. Not a perfect solution. You'd better just go with option 1 and change Javascript to handle the URLs that it will actually receive.

+3
source share

Your problem is that JavaScript works on the client side, so it will never see the ?opt=login , with which the URL will be converted internally to the server.

Besides changing your regular expression to match the new URL, the easiest workaround might be to write a server side JavaScript instruction that enters the value of the opt variable in JavaScript.

+2
source share

If this is a special case, then somehow put it as a special case. If you rewrite at all, change the general regex. How mod_rewrite works, the client never knows the rewritten URL. From the client it is only /login/ and /login/ . Only the server knows that this is really signinup.html?opt=login . Thus, there is no way to find out your regular expression or location.href.

+1
source share

If you do not use the R [R] flag in the RewriteRule, the browser (and therefore javascript) will never know the new URL. If you do not want to redirect people, you will need to add code to your login page, in which the GET parameters will be displayed as javascript on the page.

+1
source share

If you use PHP, you can create a PHP version of JavaScript for you. For example:

 $params = "?"; foreach($_GET as $key => $value) { $params = $params . $key . "=" . $value . "&"; } echo 'var urlParams = "' . $params . '"'; 

You will now have access to the urlParams variable, which looks like

 ?opt=login& 

Then, in your Javascript code, wherever you expect to use URL parameters, use urlParams .

+1
source share

All Articles