Apache: Serve all URLs on a domain with the index page, without rewriting path

apache-2.2rewriteurl

I'm writing a Backbone.js application that makes use of the HTML5 history API. I would like users to be able to create URLs of the form:

domain.com/any
domain.com/random
domain.com/paththattheuserlikes

and have all these URLs routed to my index.html page, where the Backbone router will take the path and process the request appropriately.

My question is this: how can I set up Apache to route all requests to that domain to index.html, while keeping the path in place so that the Backbone router will handle the request correctly?

I know how to do a simple Apache redirect, but I'm worried that will remove the path.

Best Answer

In your Apache config file, put the following lines:

RewriteEngine On
RewriteRule ^/[a-zA-Z0-9]+[/]?$ /index.html [QSA,L]

This will rewrite all requests that are made up of alphanumeric characters to index.html, while still preserving the query string and still appearing as being from the same path as typed. Thus, if the user went to yourdoma.in/someoldpath, index.html would be displayed but the address bar would still say yourdoma.in/someoldpath.

As mentioned by the first poster, if you want to know which path was typed, you could change the second line above to this:

RewriteRule ^/([a-zA-Z0-9]+)[/]?$ /index.html?pathtyped=$1 [QSA,L]

Which would pass the original path typed to index.html in the "pathtyped" request variable.

Related Topic