0

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.

1 Answer 1

1

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
</VirtualHost>

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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .