I have a list of url like this.
/wp-content/uploads/2023/01/Hambu-logo.png
/wp-content/uploads/2023/01/Anesa-logo.png
/wp-content/uploads/2023/01/Rock-logo.png
/wp-content/uploads/2023/01/Blue-logo.png
Using RewriteCond %{REQUEST_URI} I'd like to rewrite to another site when %{REQUEST_URI} starts with /wp-content/uploads/ and doesn't end with one of these 2 strings Hambu-logo.png or Anesa-logo.png
I've tried a lots of different expressions but it doesn't work. What I do wrong with the Negative Lookahead?
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/wp-content/uploads/.*(?!(Hambu-logo.png|Anesa-logo.png))$
RewriteRule ^wp-content/uploads(.*)$ https://www.test.com/wp-content/uploads$1 [R=302,L]
CodePudding user response:
RewriteCond %{REQUEST_URI} ^/wp-content/uploads/.*(?!(Hambu-logo.png|Anesa-logo.png))$ RewriteRule ^wp-content/uploads(.*)$ https://www.test.com/wp-content/uploads$1 [R=302,L]
The .*
before the negative lookahead consumes the rest of the string and the negative lookahead assertion always fails.
You could instead use a negative lookbehind:
^/wp-content/uploads/.*(?<!(Hambu|Anesa)-logo\.png)$
However, this can be simplified. You don't need a negative lookaround. Just use a negated expression in the condition (mod_rewrite syntax). There's no need to match the URL-prefix in both the RewriteRule
pattern and condition.
For example, in the root .htaccess
file:
RewriteCond %{REQUEST_URI} !/(Hambu|Anesa)-logo\.png$
RewriteRule ^wp-content/uploads/ https://www.test.com%{REQUEST_URI} [R=302,L]
The above matches all URLs that start /wp-content/uploads/
and do not end with either /Hambu-logo.png
or /Anesa-logo.png
. The !
prefix on the CondPattern negates the expression so it is successful when it does not match.
Since you are redirecting to the same URL-path at the target you can just use the REQUEST_URI
server variable and avoid the capturing subpattern in the RewriteRule
pattern.
Alternatively, you create another .htaccess
file in the /wp-content/uploads
subdirectory and the rule can be further simplified (no need for the RewriteCond
directive):
RewriteRule !(^|/)(Hambu|Anesa)-logo\.png$ https://www.test.com%{REQUEST_URI} [R=302,L]