Search code examples
apachehttp-redirecthttp-status-code-301rewritemap

Reduce redirects with RewriteMap


I have a RewriteMap in a file, and want to handle (ignore) optional trailing slahses. I would like to minimize the number of redirects in the trailing slash case. How do I change the apache-config?

Config:

<VirtualHost *:80>
ServerName redirtest.localhost
RewriteEngine on

RewriteMap test "txt:/tmp/redirects.txt"  #/old   /new
RedirectMatch ^/(.*?)/$ /$1
RewriteCond %{REQUEST_URI}           ^(.*)$
RewriteCond ${test:%1|NOT_PRESENT}  !NOT_PRESENT [NC]
RewriteRule .?                       ${test:%1} [NC,R=301]

result (ok):

curl -sIL 'http://redirtest.localhost/old?key=val&somemore=foobar' |grep Location 
Location: http://redirtest.localhost/new?key=val&somemore=foobar

Below works, but I would like to avoid the intermediate redirect:

curl -sIL 'http://redirtest.localhost/old/?key=val&somemore=foobar' |grep Location
Location: http://redirtest.localhost/old?key=val&somemore=foobar
Location: http://redirtest.localhost/new?key=val&somemore=foobar

Solution

  • try this:

    RewriteMap test "txt:/tmp/redirects.txt" 
    RewriteCond %{REQUEST_URI}           ^(.*\w)/?$
    RewriteCond ${test:%1|NOT_PRESENT}  !NOT_PRESENT [NC]
    RewriteRule .?                       ${test:%1} [NC,R=301]
    RedirectMatch ^/(.*?)/$ /$1