How can I disallow access to my website by its IP address?

How can I disallow access to my website by its IP address? - .htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren't comfortable in making changes in their web server's configuration file. Trying to debug .htaccess not working isn't always the easiest thing to do, however, hopefully by checking the discuss below mentioned about htaccess, apache, , , .htaccess common problems as well as the troubleshooting tips, you'll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.Problem :


I want my website to be accessible only by the domain name, not by the server’s IP address. How can I configure Apache to achieve this?



Below are the VirtualHost configurations of Apache.



<VirtualHost *:80>
ServerName not.configured
DocumentRoot /var/www
</VirtualHost>

<VirtualHost my.server.ip.address>
DocumentRoot /home/user/public_html
ServerName www.example.com
ServerAlias example.com
ErrorLog logs/example.com-error_log
</VirtualHost>

Solution :

Empty Virtual Host



With virtual hosting, all traffic is routed to an IP address and then Apache matches the hostname. When virtual hosting using NameVirtualHost is enabled, the site that responds to the IP address is the first one listed in the Apache configuration file.



So you can use a null virtualhost:



<VirtualHost 192.168.1.1:80>
DocumentRoot /dev/null
ServerName *
Redirect 404 /
</VirtualHost>


I've not tested this so may need a tweak but if you put this first in your configuration then traffic to your IP address should return a 404 error.



You would then specify your VirtualHost second.



301 Redirect



Alternatively, you could just redirect requests to the IP address to the preferred domain using a 301 redirect in your htaccess.



See: What are the most commonly used and basic Apache htaccess redirects?



for a list of rewrite rules.



You could simply redirect the user to the named host:



# Uncomment the line below if not previously added in the file
# RewriteEngine On

# Rule to redirect to the named host
# Replace [xx.xx.xx.xx] woth your host's IP address
# Replace [yourdomain.com] with your host's proper URL
RewriteCond %HTTP_HOST ^xx.xx.xx.xx$
RewriteRule (.*) http://yourdomain.com/$1 [R=301,L]


I didn't ttest this to see if it works or not, but at least it's an idea you can build on, for a proper solution.


Additionally, if you would like to do some further testing, give the htaccess tester tool a try. It allows you to specify a certain URL as well as the rules you would like to include and then shows which rules were tested, which ones met the criteria, and which ones were executed.

Comments

Popular posts from this blog

Rewrite in Mediawiki, remove index.php, .htaccess

.htaccess rewrite wildcard folder paths from host

Using .htaccess to set a cookie and 301 redirect