php - Mod Rewrite and 404 redirect
Get the solution ↓↓↓I want make websitename.com/file.php become websitename.com/file/ and after browsing thru StackOverflow, with countless try and error, this is what I got and it is working.
RewriteEngine on
RewriteRule ^(.*)\/$ $1.php [NC]
I also added this to header.php so that if any filename shows up with the .php extension, it will redirect to the 'slashed' URL I wanted.
$NoPhpUrl = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
$NoPhpUrl = $NoPhpUrl .'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if(strstr($NoPhpUrl , ".php"))
{
$NoPhpUrl = str_replace(".php","/", $NoPhpUrl );
header("Location: ".$NoPhpUrl );
}
The issue I have currently is when I type this link websitename.com/file (without slash at the end), it will go to a 404 page.
I'm ok with the 404 page if the file does not exist in the directory. But if it does, is there a way to force the slash to appear at the end of the url (if file exist) without making it go to 404?
Answer
Solution:
You should try your rules this way and also turn off multiviews. I added force trailing slash as I would do it in Apache instead of PHP. Server side should be preferred versus code redirects.
Options -MultiViews
RewriteEngine on
#force trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$ [NC]
RewriteRule ^(.*)$ /$1/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)/$ $1.php [L,NC]
Answer
Solution:
check in your if condition, you're replacing .php with /. so, this is the reason why you can't access in path without /. check out.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: illegal string offset
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.