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:

├── 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
#Alias /dir "/tmp/dir"
#<Directory "/tmp">
#       AllowOverride All
#       Require all granted

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
Alias /dir "/tmp/dir"
<Directory "/tmp">
       AllowOverride All
       Require all granted

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


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.


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...

<VirtualHost *:80>
  ServerName    www.example.com
  ServerAlias   example.com
  DocumentRoot  /var/www/example.com/
  Alias /scripts/ /var/www/scripts/
  RewriteEngine on
  RewriteRule   ^file.js$ file.php

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 containing file.js. Depending on the AllowOverride 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.

  • Please see my revised answer. I am specifically interested in knowing if this can be done using .htaccess files. Thank you anyway !! – thyandrecardoso Jul 21 '14 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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