skip to Main Content

Trying to set a .htaccess file for direct all URLs that end in .php or no file extension at all to index.php. So URLs like mysite.com/about and mysite.com/news.php will go to index.php, but mysite.com/someimage.jpg and mysite.com/mystyle.css will be handled normally.

I thought I had it when I tested with regular old PHP but something doesn’t seem to be translating in the .htaccess file. These are the two rules I’ve come up with:

RewriteRule [A-Za-z0-9]*$ "index.php" [L] # URLs with no extension

RewriteRule [A-Za-z0-9]*.php$ "index.php" [L] # ending in .php

With these rules, files like CSS and images aren’t being served, everything is still going to index.php so the server will serve index.php when the browser asked for a stylesheet. I’ve tried commenting out the .php rule so only the ‘no extension’ rule is applied, same result. I’ve tried adding a slash at the beginning like there would be in a URL and that actually breaks things so none of the rules are applied.

What tiny yet obvious detail am I missing here?

2

Answers


  1. Your extensions end in alpha characters so [A-Za-z0-9]*$ matches the jpg of .jpg and css of .css.

    I think:

    RewriteRule (.php|^[^.]+)$ "index.php" [L]
    

    will accomplish what you want. That says if the file ends with .php or the full path doesn’t have a period in it send it to index.php.

    https://regex101.com/r/AE8AjY/1/

    compared to your regex(s):

    https://regex101.com/r/AE8AjY/2/ (combined the two rules into one by making the .php optional)

    Login or Signup to reply.
    1. Main problem is not using start anchor in your rules.
    2. Rules can be further optimized.

    Have it this way:

    RewriteEngine On
    
    # ignore index.php
    RewriteRule ^index.php$ [L,NC]
    
    # URLs with no extension OR URLs ending with .php
    RewriteRule ^[w-]+(?:.php)?$ index.php [L,NC]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search