1

I have this rule on my .htaccess that doesn't work as I would expect:

RewriteRule ^/rg$ /download/file_1.pdf [NC,L]

I would like to redirect all the requests from www.example.com/rg to download this file: www.example.com/download/file_1.pdf but so far nothing happens...

Am I missing something?

1
  • thanks MrWhite, I'm really a newbie... ^_^ Commented May 7, 2019 at 9:57

1 Answer 1

0

In .htaccess the URL-path that is matched by the RewriteRule pattern does not start with a slash. So, the regex should be ^rg$, not ^/rg$. In other words:

RewriteRule ^rg$ /download/file_1.pdf [NC,L]

Specifically, the directory-prefix that leads to the .htaccess file is first removed from the requested URL-path before the match occurs. This directory-prefix always ends with a slash, so the URL-path never starts with a slash.

This contrasts to when the directive is used in a server (or virtualhost) context, when you do need the slash prefix, since it matches the full URL-path (there is no directory-prefix in a server context).

3
  • thanks a lot, but what if I require to have a slash before the string "rg"? For example to avoid matching other string that ends with "rg"? Commented May 7, 2019 at 10:03
  • 1
    sorry, now I get it... "This directory-prefix always ends with a slash, so the URL-path never starts with a slash." Thanks again Commented May 7, 2019 at 10:06
  • Yes, the regex ^rg$ actually matches the requested URL /rg (exactly). This is unique to mod_rewrite (in a directory/.htaccess context). By contrast, the mod_alias directives Redirect and RedirectMatch would require you to match against the slash prefix (ie. the full URL-path).
    – MrWhite
    Commented May 7, 2019 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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