Jarrod Nettles
Jarrod Nettles

Reputation: 6283

htaccess rule - Take the Place of Symlinked Files

I'm working on this legacy project that has a rather odd setup that I'm looking to get rid of but my htaccess skills are a little lacking in this department.

Here's the directory structure.

/index.php
/www
  page1.php -> symlink to index.php
  page2.php -> symlink to index.php
  page3.php -> symlink to index.php

/www is the public directory and people visit http://site/page1.php. However, each of those files with an * actually symlinks to /index.php.

I find this arrangement idiotic and would like to get rid of the symlinks and simply have any /www/*.php request simply point at index.php without the page actually redirecting to index.php.

Any ideas for an htaccess rule(s) that could solve this problem? At its most basic core, I'd like to keep the same functionality without having to have a thousand symlinked files.

Upvotes: 1

Views: 150

Answers (1)

Jon Lin
Jon Lin

Reputation: 143906

It looks like the index.php file is not in your document root (which I'm assuming is www), and because of that, I don't think there's a way you can do this from your .htaccess file. In order to access something outside of your document root, you'll need to setup an alias in either your server config or your vhost config:

# Somewhere in vhost/server config
Alias /index.php /var/www/path/to/index.php

# We need to make sure this path is allowed to be served by apache, otherwise
# you will always get "403 Forbidden" if you try to access "/index.php"
<Directory "/var/www/path/to">
        Options None
        Order allow,deny
        Allow from all
</Directory>

Now you should be able to access /var/www/path/to/index.php. Note that other files in the /var/www/path/to directory is safe as long as you don't create an Alias (or AliasMatch or ScriptAlias) that points to them. Now that you can access index.php via the /index.php URI, you can setup some mod_rewrite rules in the .htaccess file in your document root (www) to point things to index.php:

# Turn on the rewrite engine
RewriteEngine On

# Only apply the rule to URI's that don't map to an existing file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all requests ending with ".php" to "/index.php"
RewriteRule ^(.*)\.php$ /index.php [L]

This will make it so when you request http://site/page1.php, the browser's address bar is unchanged but the server actually serves /index.php, which is aliased to /var/www/path/to/index.php.

You can tweak the regular expression ^(.*)\.php$ to something more appropriate if need be. This just matches anything that ends with a .php, including /blah/bleh/foo/bar/somethingsomething.php. If you want to limit the directory depth, you can tweak the regular expression to ^([^/]+)\.php$, etc.

Upvotes: 1

Related Questions