Apache HTTP LocationMatch Redirect using Negative RegEx

apache-2.4redirectregex

I'm trying to create a Redirect using Apache HTTP Server's mod_alias and core on my system:

# cat /etc/redhat-release 
Red Hat Enterprise Linux Server release 7.1 (Maipo)
# rpm -q httpd
httpd-2.4.6-31.el7_1.1.x86_64
# 

requirement is to redirect all requests, except for request to /server-status

# cat /etc/httpd/conf.d/_default.conf 
<VirtualHost *:80>
    ServerName _default_
    <LocationMatch "^/!(server-status)(.*)?">
        Redirect / http://X/
    </LocationMatch>
</VirtualHost>
# 

I believe my issue is somewhere with regex, as I'm getting 404 no matter what URL I hit.

Best Answer

1 - You can do it using mod rewrite https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html

<VirtualHost *:80>
    ServerName _default_
    RewriteCond %{REQUEST_URI} !^/server-status
    RewriteRule (.*) http://X$1 [L,R=301]
</VirtualHost>

2 - To use Mod_Alias you need RedirectMatch http://httpd.apache.org/docs/current/mod/mod_alias.html

<VirtualHost *:80>
    ServerName _default_
    RedirectMatch 301 ^/(?!server-status)(.*) http://X/$1
</VirtualHost>

3 - more info:

  • once configuration has been changed, Apache needs to be restarted
  • the server needs to be different else you will have a redirect loop

4 - Bonus

(.*) = catch all in regexp

$1 = result var

R = redirect status code, here you have the list:

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

L = flag which mean Last, here you have the flag list codes:

https://httpd.apache.org/docs/2.4/rewrite/flags.html

5 - Even more... if you really want to use LocationMatch syntax is :

<VirtualHost *:80>
    ServerName _default_
  <LocationMatch "^/(?!server-status)(.*)">
    Redirect / http://X/
  </LocationMatch>
</VirtualHost>