An Apache trick: using directories to create redirections

May 9, 2016

Suppose, not entirely hypothetically, that you're using Apache ProxyPass directives as a reverse proxy to map /someurl/ on your website to another web server. You generally have to redirect the URL with the trailing slash, but of course you would like a request for a plain '/someurl' to also work right instead of just getting a 404 status response. Here, 'work right' means that you'll generate a redirection from '/someurl' to '/someurl/'.

It's certainly possible to do this with one of the various Apache directives for explicit redirections (I'd use RedirectMatch). But often there's an easier way: use a real filesystem directory. If somedir is a directory in the Apache document root and you send a request for '/somedir', Apache's default behavior is to send exactly the redirection we want. And Apache doesn't care if the '/somedir/' URL is being diverted somewhere other than the filesystem (via ProxyPass or other directives); it will still send that redirection regardless.

So we can just do 'mkdir /docroot/someurl' and everything will work. The directory contents don't matter; I tend to put a README file there with a note about how the directory is just there for the redirection and actual contents in it will be ignored.

(This redirection trick happens automatically if you're using .htaccess files in a directory to control, say, internal redirections. However there are various reasons for not using .htaccess files, including centralizing your configuration in one easily visible place instead of spraying it all over the filesystem in a bunch of nominally invisible files.)

Back when I wrote my entry on ProxyPass, I theorized about using this trick. I can now say that we've actually done this in our configuration and it works fine.

(This trick is a very old one, of course; I'm sure people have been doing it in Apache for ages. I just feel like writing it down explicitly for various reasons.)

Comments on this page:

From at 2016-05-13 15:16:38:

I would avoid this approach because it separates the redirection from the rest of the configuration, making it less obvious what is happening when only looking at the configuration file.

Written on 09 May 2016.
« You can't use expvar.Func to expose a bunch of expvar types
The difference between 'Delete' and 'Destroy' in X window managers »

Page tools: View Source, View Normal, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Mon May 9 22:01:33 2016
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.