Saturday, January 10, 2015

centos - Make Apache server only accept requests to domain rather than IP



I have a CentOS server running Apache 2.2.15. If the IP address of the server is 198.51.100.4 and I write in browser http://198.51.100.4 it goes on my website.




I want to prevent this. I want my website to be accessible only on the FQDN i.e. http://example.com/.



How can I configure my server so the website is not accessible when I visit the IP address?


Answer



You can use Alias * to catch any other trafic than thoose allowed in your virtual host, for this you have to use in the last position a virtual host with * as alias.



Like that only defined domain will be served.




ServerName mywebsite.com

DocumentRoot /var/www/default
...



ServerName another.mywebsite.com
DocumentRoot /var/www/another
...



# /!\ THIS HAS TO BE ON THE LAST POSITION /!\

# [ Server Domain ]
ServerName localhost
ServerAlias *
# [ Cancel trafic ]
RewriteRule .* - [END,R=406]
# [ Custom Log ]
CustomLog ${APACHE_LOG_DIR}/other.log combined




In my example only mywebsite.com & another.mywebsite.com will be allowed, all other domains or IP will have trafic cancelled.



To cancel the trafic you can use a redirect to - and then add an error code, for example i used a RewriteRule to redirect to 406 Not Acceptable (R=406).



Here you can find the list of redirect codes:
https://fr.wikipedia.org/wiki/Liste_des_codes_HTTP


No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...