Apache2, Allowing from Only your Localhost, Specific Ips and Redirecting for others
Apache, ubuntu October 14th, 2007What i wanted
I have a server in the office, and wanted all people on the network to be able to access the webservers root path (/var/www/) but all external ip’s to be redirected to /var/www/some/other/dir
htaccess file
My wordpress will not let me write “dot htaccess”, so where you see me say “htaccess”, please put a “.” (dot) infront of it.
How todo it
Firstly with mod_rewrite
If you don’t have access to your /etc/apache2/sites-available files or are on a shared host, then this can be done entirely from your htaccess file, HOWEVER %{HTTP_ .. can be spoofed, so is not entirely secure.
Firstly lets put the htaccess in place in the root directory of our web server (/var/www/)
sudo vim /var/www/htaccess
And in here we need to add the following code:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^localhost
RewriteCond %{HTTP_HOST} !^192\.168\.
RewriteRule (.*) /some/other/folder/ [L]
That should all be pretty self explanatory, but if not, explanation as follows:
- RewriteEngine on - Enable mod_rewrite
- RewriteCond %{HTTP_HOST} !^localhost - If the host is not localhost
- RewriteCond %{HTTP_HOST} !^ 192\.168\. - If the ip is not in the 192.168 range
- RewriteRule (.*) /some/other/folder/ [L] - Redirect all requests, HEAD, GET, POST to the /some/other/folder directory, the [L] flag stops processing
More information on mod_rewrite can be found at the following pages
Secondly, secure with apaches sites-available file
Firstly, we need to open your sites configuration file (default, or ssl, or mysite perhaps).. mine is called ‘default’
cd /etc/apache2/sites-available/
sudo gedit default
We then need to add in the correct allow from. More documentation on this can be found here: Apache2 Allow From Documentation
I wanted allow 192.168 & localhost to be able to view /var/www/, but give everyone else access /var/www/some/other/folder/
This is how i edited my default file accordingly.
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from 192.168
allow from localhost
</Directory>
<Directory /var/www/some/other/folder/>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all
</Directory>
Again this should all be self explanatory. If not, reread it.
Conclusion
I’m sure there’s 100 and 1 ways todo this, some possibly more complicated, and others maybe more simple. Please post links to other useful similair tutorials, comments on security, improvements are all welcome.
I am glad to share the knowledge i have learned with other people to save them wasting their time re-learning what i have already found out ![]()

Recent Comments