Search code examples
apache.htaccessurl-rewriting

Best practice for redirecting URLs


I have a domain 'example.com'. What I want to do is having my URL's as clean and readable as possible For Example:

  • example.com/login
  • example.com/about-us
  • etc.

but since there are file extension and my files are not all in the servers (Apache) document root I need to redirect them:

  • example.com/login => example.com/authorization/login/login.php
  • example.com/about-us => example.com/pages/about-us/about-us.html

But what is the best way too achieve this kind of behaviour? For testing purposes I did it using Apaches .htaccess file like this:

RewriteEngine On
RewriteRule ^login/?$ /authorization/login/login.php
RewriteRule ^about-us/?$ /pages/about-us/about-us.html

This however doesn't seem like the best way way to do for a public website.

Edit: This assumption is mainly based on articles like this or this:

For security, the .htaccess file is much more accessible than standard Apache configuration and the changes are made live instantly (without the need to restart the server). This grants users permission to make alterations in the .htaccess file, giving them a lot of control over the server itself. Any directive placed in the .htaccess file, has the same effect as it would in the Apache configuration itself. It’s also important to note that Apache generally discourages the use of .htaccess if the user can access the Apache configuration files themselves.


Solution

  • The additional information you provided addresses the question where you implement your rewrite rules. Not whether using rewrite rules is good or bad in the first place.

    Indeed one should always prefer to configure the http server in its central configuration. Not in distributed configuration files.

    If enabled, you can indeed add distributed configuration files (often called ".htaccess"), that feature is provided mainly for situations where you don't have access to the central configuration (read: really cheap web service providers). That feature is typically miss used today by web application frameworks that rely on being able to write its own configuration into such files. That works and is convenient for unexperienced people who want to operate such applications. But it obviously raises massive security threats ... A software should obviously never be able to alter its own implementation.

    In addition to the security concerns it also is a valid point to address the http server's performance. Using distributed configuration files definitely has a negative impact. For each and every request all such files on the requested path have to be read and interpreted. The file hierarchy adds complexity to the fulil setup. And it makes debugging a much more difficult task.

    So yes, usually you should use the central configuration of the http server. Unless you have specific reasons not to ;-)