1
\$\begingroup\$

I want to redirect all pages under a certain directory to a single file, like so:

  • /dir/a/dir/new
  • /dir/b/dir/new
  • /dir/new/dir/new

With the straightforward

RedirectMatch 301 ^/dir/ http://example.com/dir/new

I get a redirect loop, since /dir/new redirects to itself. I replaced it with a regular expression

RedirectMatch 301 ^/dir/($|[^n]|n$|n[^e]|ne$|ne[^w]|new.) http://example.com/dir/new

which matches all URLs except the desired one. This works, but it's obviously the 'wrong' way to do it. What's a better way?

\$\endgroup\$
0
1
\$\begingroup\$

RedirectMatch doesn't redirect all pages under a certain directory to a single file:

Then any request beginning with URL-path will return a redirect request to the client at the location of the target URL. Additional path information beyond the matched URL-path will be appended to the target URL.

That is, a request for /dir/a/blah would get redirected to /dir/new/blah, not to /dir/new as you said you wanted.

As a solution, I suggest using mod_rewrite:

RewriteEngine on
RewriteCond $0 !=/dir/new
RewriteRule ^/dir/.* /dir/new [R]
\$\endgroup\$
0
1
\$\begingroup\$

It seems you're looking for a negative lookahead: path starting with /dir/ and not followed by new$:

RedirectMatch 301 ^/dir/(?!new$) http://example.com/dir/new
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.