Search code examples
apache.htaccesshttp-redirectmod-rewriteurl-rewriting

Simple rewrite rule is not working on Apache server


When trying to create URL rewrite rules on my server, I ran into some problems so wanted to test if it was working at all with a more simple case: The URL example.com/test should be rewritten as example.com/index.php, a real page that exists on my site.

Here is the full content of my .htaccess file:

AcceptPathInfo Off

SetEnv PHP_VER 5_3
SetEnv REGISTER_GLOBALS 0

RewriteEngine On
RewriteRule   test.php   index.php

And the result when I enter the URL example.com/test.php:

404 Not Found: The requested URL was not found on this server.

I made the .htaccess document slightly more simple for this test than it usually is. Usually, I also have the following rules in the document:

# Redirect from non-www to www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


# Redirect from HTTP to HTTPS

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

These rules have always worked as they should. Is there something wrong with my test rewrite rule, and if not, why are the rewrite rules working for www and HTTPS redirection?

This is the structure of the files on my server:

| .htaccess
| www
| -- index.php

Solution

  • With your shown samples, please try following htaccess rules file. Place your https and www implementing rules at top of your file.

    Make sure your htaccess and index.php files are in root directory. Please make sure to clear your browser cache before testing your URLs.

    RewriteEngine On
    
    # Redirect from HTTP to HTTPS
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule  ^test/?$   index.php [NC,L]
    

    Change the structure of htaccess as follows with your shown samples apart from few minor other changes in htaccess(like fixed regex for redirection, used NE flag in redirection, combined Rules for https and www redirects etc; to improve your rules file)

    | .htaccess
    | www
    | -- index.php
    | -- .htaccess (new)