death to the tilde
April 3rd, 2008 Posted in LinuxWell, for the past 2 hours, I’ve been fighting with mod_rewrite to get rid of the ~ character that apache shoves into a url for the UserDir directive by default. Since having a url like http://example.com/username/foo.html is far neater than http://example.com/~username/foo.html, and mostly because hughesjr has been after me to fix it, I finally have a solution.
So, for those of you thinking “uh, there’s an example for doing this right in the httpd docs”… let me save you the trouble. It doesn’t work. the instructions at http://httpd.apache.org/docs/2.2/rewrite/rewrite_guide.html cause the url to be rewritten properly, but then promptly 404’s because it looks in /var/www/html/u/username/ for the files. Afer digging around in google, and working with some friendly folks in #apache (yes they do exist) we have a solution:
RewriteEngine On
#RewriteLog logs/rewrite.log # Uncomment for rewrite logging
#RewriteLogLevel 3 # uncomment for verbose logging
RewriteCond %{REQUEST_URI} ^/([^/]+)
RewriteCond /home/%1 -d
RewriteRule ^/([^/]+)(.*) /home/$1/public_html/$2
Take that bit of code, and drop it into /etc/httpd/conf.d/homedir.conf or wherever else you’d like in your httpd configs, and reload apache. From there you’ll be able to use shorter, sexier UserDir urls for your user’s webpages.