How to refer to the current directory in htaccess
Asked Answered
P

2

6

I need to get dynamically the current directory in which my .htaccess file is located. Is that possible ? (A variable maybe ?).

Something like : %{SCRIPT_FILENAME}

Thank you in advance.

EDIT : If with regular expressions ? how should it look like ?

Prussia answered 4/3, 2013 at 10:45 Comment(3)
did you check this list ?Ladoga
my be this helps #1200848Rysler
Apparently, it is impossible to obtain the current directory path in .htacess files via an expression. Just one of a handful of remarkable limitations of using Apache directives in .htaccess files.Diatonic
T
3

Actually Apache still does not have pathinfo($,PATHINFO_DIRNAME) function like PHP does.

So on, there have been solutions based on the usage of %{REQUEST_URI}, like this example:

  RewriteRule ^(.+)/$ /path-dirname/$1 [R=301,L]

Regarding your issue, this may work for you:

  RewriteCond %{REQUEST_URI} ^(.+)/$
  RewriteRule ^.+/$ %1 [R=301,L]
Thyrse answered 4/3, 2013 at 11:25 Comment(0)
W
1

Got myself stuck with the same problem today, and it seems we still don't have such method or variable available some 11 years later ... so here is a solution to compute it using mod_rewrite

Simply put those lines in your .htaccess file :

# add some nasty folder name in request path
RewriteRule ^/?(.*)$ __PWD__/$1 [QSA]

# split to identify current directory and relative file
RewriteCond "%{REQUEST_FILENAME}" ^(.*/)__PWD__/(.*)$

# define environment variables and restore original path
RewriteRule ^ %1%2 [QSA,E=dir:%1,E=req:%2]

This code will set 2 environment variables :

  1. dir: full path to current folder
  2. req: subsequent request filepath

Afterwards, you can use those with %{ENV:dir} and %{ENV:req} but beware they don't get re-computed automatically!

Reminder: be sure you have mod_rewrite enabled and RewriteEngine On somewhere before the suggested code!


Example usage:

RewriteCond "%{ENV:dir}API/%{ENV:req}.php" -f
RewriteRule ^(.*)$ API/$1.php [QSA]

Or using full path:

RewriteCond "%{ENV:dir}API/%{ENV:req}.php" -f
RewriteRule ^ "%{ENV:dir}API/%{ENV:req}.php" [QSA]

Know you can update 'req' variable together with rewriting as follow:

RewriteCond "%{ENV:dir}API/%{ENV:req}.php" -f
RewriteRule ^(.*)$ API/$1.php [QSA,E=req:API/$1.php]

Same using environment variables:

RewriteCond "%{ENV:dir}API/%{ENV:req}.php" -f
RewriteRule ^ API/%{ENV:req}.php [QSA,E=req:API/%{ENV:req}.php]
Witkowski answered 25/7 at 14:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.