Apache
Displaying PHP Files as Text on Server
I attached a php file for my last post but didn't want to have to rename it to a .txt file to prevent apache from serving it as php. The solution? Edit the .htaccess file in my uploads folder:
RemoveHandler php
RemoveType php
Automatic Virtual Hosts in Apache using mod_rewrite
I use Apache on my Mac for most web development. My process, up until now, for creating a new local site has been as follows:
- Add entry to my hosts file
- Create directory in my webroot
- Create neccesary databases
- Add entry to my virtual hosts file restart apache
I got tired of creating nearly identical Virtual Host entries so I decided to automate the process. To make things simple- I decided to have all my urls end in the ".local" extension... so the local copy of this website would be sambernard.net.local.
First Attempt: mod_vhost_alias
I started out using mod_vhost_alias- the setup was pretty simple, and required only two lines of code in my apache config file:
UseCanonicalName Off
VirtualDocumentRoot /usr/local/apache/vhosts/%0
Setting UseCanonicalName Off tells Apache to use the host name provided by the client instead of the one set in your Apache config. [http://httpd.apache.org/docs/2.0/mod/core.html#usecanonicalname]
The %1 and %2 in the VirtualDocumentRoot directive represent the first two parts of the domain name, separated by a period- so for sambernard.net.local apache would look for a directory called /var/www/sambernard.net/. You can read more about mod_vhost_alias here: http://httpd.apache.org/docs/2.0/mod/mod_vhost_alias.html.
This worked great- however I could no longer access "localhost" or any other virtual hosts.... only domains that matched the "domain.com.local" were recognized. Someone suggested I put the directive in its own Virtual Host, however I could never get it play with my hard coded Virtual Hosts.
Second Attempt: mod_rewrite
For more flexibility I decided to try using mod_rewrite and came up with the following:
<VirtualHost *>
ServerAlias *.local
DocumentRoot /var/www
<Directory "/var/www/">
allow from all
Options +Indexes
</Directory>
RewriteEngine on
RewriteCond %{SERVER_NAME} ^([a-zA-Z0-9-_]*)\.([a-zA-Z0-9-_]*)\.local
RewriteRule (.*) /%1.%2/$1 [L]
RewriteCond %{SERVER_NAME} !^localhost$
RewriteCond %{SERVER_NAME} !^sam-bernards-macbook.local$
RewriteRule (.*) - [F]
</VirtualHost>
I created a catch-all virtual host. Using mod_rewrite, I checked for any domains that matched the pattern I wanted(domain.com.local). If the domain matched, then the url was rewritten to the corresponding directory (/var/www/domain.com/). If the directory does not exist you get a 404 Not Found error. Additionally, I added a check for other domains, so that anything other than my computer name or localhost would get a 403 Forbidden response. This isn't strictly neccesary, but if I ever used something like this on a public server it would prevent from people pointing their domains at my site.