In web applications, it may sometimes be necessary to allow access only to specific IP addresses and redirect all other requests to a different URL. This is often used for
maintenance modes, development environments, or IP-based special access restrictions. On the Apache web server, this can be easily achieved with special rules written in the .htaccess file.
Code Explanation
# Check IP addresses
RewriteCond %{REMOTE_ADDR} !^31\.143\.234\.25$
RewriteCond %{REMOTE_ADDR} !^31\.143\.234\.23$
RewriteCond %{REMOTE_ADDR} !^88\.209\.248\.203$
# Redirect if it is a different IP address
RewriteRule ^(.*)$ https://www.ekasunucu.com/iletisim [R=302,L]
What does this rule do?
-
The
RewriteCondlines check the IP address of the incoming request. -
If it is not (
!) from the specified IP addresses, i.e., not in the list, the RewriteRule comes into play. -
Redirects all incoming requests to
https://www.ekasunucu.com/iletisimwith a 302 (temporary) redirect.
Usage Areas
-
Showing the active version of the site only to certain developers and redirecting all remaining users to the contact page.
-
Allowing only the system administrator to access a site that is under maintenance.
-
Allowing bots or testing tools from specific IP addresses to access.
Things to Consider
-
The
mod_rewriteApache module must be active. Otherwise, the rules will not work. -
AllowOverride Allmust be defined in the directory where the.htaccessfile is located. -
\.must be used in IP addresses because a dot (".") in regex means any character. -
If you want to make the redirect type permanent instead of
302, it can be changed toR=301.
IP-based access control and redirection configuration with .htaccess is an important practice in terms of the security and control of web applications. With this method, you can define special permissions for specific IP addresses and redirect all other accesses to alternative pages. It provides great convenience during development processes or maintenance.