0

I'm having trouble with my Apache redirects and rewrites, and I have no idea why what I've got doesn't work. This is the goal:

Browser URL:         http://127.0.0.1/app-gallery/all
Redirect (301) to:   http://127.0.0.1/apps/all
Serve file from:     /en/apps/all

In my httpd.conf, I have the following:

LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
RewriteEngine On

RedirectMatch 301 ^/app-gallery(.*) /apps$1

RewriteCond %{REQUEST_URI} !^/en/
RewriteRule ^(.*)$ /en/$1 [L,QSA]

With the last two lines (condition and rule) included, my browser does not get a 301 redirect, just a 404. If I take the last two lines out, the redirect happens - but then I'm obviously not serving a file from the /en/ directory like I need to be.

Shouldn't the redirect happen, resulting in a new request that doesn't get redirected, followed by application of the rewrite?

Also, I have a number more of these RedirectMatch lines in there (after the relevant one), but I removed them for sake of simplifying my example.

jcovert
  • 550
  • 1
  • 7
  • 21

1 Answers1

1

For simple redirections always go for redirect, but if you need to use mod_rewrite, better stick with it, that is, mixing redirect and rewrites is going to cause confusion, like this actual case.

What is happening is Rewrite is happening first, and both your rewrite directives and redirectmatch apply over the same thing (both origin are not /end/, defining redirect first does not make it happen first.

What you want is to describe something that will go in the order you want:

RewriteRule ^/app-gallery(.*) /apps$1 [R=301]
RewriteRule ^/(?!en)(.*) /en/$1 [L,QSA]

This redirects in the order of preference you want.

If the final destination is in the filesystem, you could try to use Redirect and Alias with I believe something like this, but I am not sure about this since I don't know your setup well enough:

Redirect permanent /app-gallery/ /apps/
AliasMatch ^/apps/(.*) /filesystem/path/to/apps/$1
Daniel Ferradal
  • 2,727
  • 1
  • 13
  • 19
  • Thank you - that makes a lot of sense. For whatever reason, the R=301 RewriteRule wasn't actually doing a redirect for me - that's how I discovered RedirectMatch. I used an online htaccess tester, and it says they SHOULD have been redirecting, so I'll have to look into it a bit more. Thanks! – jcovert Feb 27 '17 at 23:30