Search code examples
regex.htaccessurlurl-rewritingpermalinks

Removing index.php from url using .htaccess even if the user requests it


I never want index.php to show up in my URL, even if the user inputs it. Is this possible?

This is variation whatever after several tries. I've come close a few times but this is where it's at for now.

RewriteEngine On  
RewriteBase /sub-dir/  
RewriteCond %{REQUEST_URI} index\.php$  //If URL ends in index.php
RewriteRule (.*)index\.php $1  //Somehow remove index.php from the url
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule . index.php [L]  

Currently I have permalink set up where if the user enters domain.com/sub-dir/my-perma-lin/ it generates a string on the page based on my-perma-link to look like My Perma Link. What I'd like is if the user submits any URL ending in index.php it just removes that from the URL but leaves everything else as is.

domain.com/sub-dir/index.php --> domain.com/sub-dir/
domain.com/sub-dir/my-perma-link/index.php --> domain.com/sub-dir/my-perma-link

I've written quite a few rules in http://htaccess.madewithlove.be/ that work perfectly but when I upload it (to Dreamhost) nothing works.

This for example should work according to the the tester

RewriteEngine On  
RewriteBase /sub-dir/  
RewriteCond %{REQUEST_URI} \.php  //Not needed but thought it would/should help
RewriteRule (.*)(index\.php)+ $1 [L,R=301,NC]

But it just removes everything after /sub-dir/

I'm either missing something super obvious or it's not possible ...


Solution

  • You need to add some flags to your rule:

    RewriteEngine On  
    RewriteBase /sub-dir/  
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php(\?|\ )
    RewriteRule ^ /%1 [L,R=301]
    RewriteCond %{REQUEST_FILENAME} !-f  
    RewriteCond %{REQUEST_FILENAME} !-d  
    RewriteRule . index.php [L]  
    

    You can ditch the RewriteCond %{REQUEST_URI} index\.php$ condition, as that's being checked by the regex in the RewriteRule. You need to include a $ at the end of the regex, and include the flags L to stop rewriting and R=301 to redirect.