I have the following .htaccess
within a subdirectory:
RewriteEngine on
RewriteRule ^file.js$ file.php
The directory, containing the above and other files looks like this:
dir/
├── index.html
└── js
├── file.php
└── .htaccess
I want my file.js
to be internally redirected to the file.php
.
When I have dir
under /var/www/html/
, and my vhost
definition looking like this:
DocumentRoot /var/www/html
<Directory "/var/www/html">
AllowOverride All
Require all granted
</Directory>
#Alias /dir "/tmp/dir"
#<Directory "/tmp">
# AllowOverride All
# Require all granted
#</Directory>
it works!
However, when I move dir
to /tmp/
and change the vhost
to look like this:
DocumentRoot /var/www/html
#<Directory "/var/www/html">
# AllowOverride All
# Require all granted
#</Directory>
Alias /dir "/tmp/dir"
<Directory "/tmp">
AllowOverride All
Require all granted
</Directory>
the redirect does not work any more, though I still can access other files such as index.html
.
The logs show me that the rewrite prepends the DocumentRoot
to the full path of my file.php
and, thus, giving me a File does not exist message
Question:
How do I write an .htaccess that is agnostic to where it is placed, and just makes an internal redirect from one specific file to another?
Please keep in mind that, while I am able to change the the main vhost
config to deal with this problem, my goal is to do this using only .htaccess
.
Best Answer
The best practice is to move your configuration directives to the actual Apache configuration file (and disallow .htaccess files completely).
In this case that will solve your problem because you're no longer dependent on a filesystem location for your directive to take effect...
If you're not the system administrator and don't have access your Apache config, well, your question wouldn't be on topic but that's beside the point, you could solve the issue by creating a (copy)
.htaccess
file in the directory containingfile.js
. Depending on theAllowOverride
directive the real administrator configured for you, you normally are allowed to place .htaccess file in any directory and subdirectory Apache has access to. You're not restricted to the DocumentRoot.