Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apache2 mod_rewrite per-directory request in rewritecond

My current .htaccess file works but I think that is not the best way of solving this problem and I'm afraid that it won't work in the future with more rewrite rules.

.htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteRule ^files/(.*) files/$1 [END]

RewriteRule ^(.*) files/$1 [END]
</IfModule>

The server checks if the url leads to "files" folder and only rewrites if it leads somewhere else.

I tried something like

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteRule !^files/(.*) files/$1 [END]
</IfModule>

but it doesn't work since I can't pass $1 variable. I wan't something like

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{URL_STARTING_AT_THIS_POINT} ^files/*
RewriteRule ^(.*) files/$1 [END]
</IfModule>

or

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !%{URL_TO_THIS_HTACCESS}/files/*
RewriteRule ^(.*) files/$1 [END]
</IfModule>

I didn't find any server variables for this. I want to compare the first parameter from RewriteRule (^files/) in RewriteCond and I don't find the correct server variable.

like image 579
Thomas Sablik Avatar asked Oct 30 '25 00:10

Thomas Sablik


1 Answers

I didn't find any server variables for this.

The server variable you are probably after is REQUEST_URI - which contains the URL-path, including the slash prefix. For example:

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

Or, you could simply write this:

RewriteRule !^files/ files%{REQUEST_URI} [L]

However, your original directives are probably OK, although could be tidied a bit:

RewriteRule ^files/(.*) - [L]
RewriteRule (.*) files/$1 [L]

The hyphen in the substitution can be used when there is no change to the URL. I don't think you really need the END flag here, unless you have other directives that might conflict?

like image 137
MrWhite Avatar answered Nov 01 '25 14:11

MrWhite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!