Thursday 22 April 2021

HTACCESS + PHP | Forcefully Add Ending Slash (/) In URL On Rewrite Rule

 


You can download the whole folder from:
https://unpossiblepog.com/codes/PHP+HTACCESS/HTACCESS-Forcefully-Add-Slash-At-The-End-Of-URL

.htaccess
RewriteEngine on

RewriteRule ^([^\.]+)/$ $1.php [NC,L]

ErrorDocument 404 http://%{HTTP_HOST}/<project-folder>/error.php?ref=%{HTTP_HOST}%{REQUEST_URI}

-----------------------------------------
error.php

<?php

if(isset($_GET['ref'])) {

$path_name=$_GET['ref'];

$file_name_array=explode("?", $path_name);

//echo $this_path."<br/>";

//echo $file_name_array[0]."<br/>";

if(isset($_SERVER['HTTPS'])){$http_https = "https://";}else{$http_https = "http://";}

$file_name=$http_https.$file_name_array[0];

header("location: ".$file_name."/");

  //echo $file_name."<br/>";

}

?>

-----------------------------------------
index.php

<h1>This is INDEX file.
</h1>
-----------------------------------------

about.php

<h1>This is About page.</h1>
-----------------------------------------
hello.php

<h1>This is hello page.</h1>

=======================


Subscribe my Channel:- http://www.youtube.com/user/SanketRooney?sub_confirmation=1

Facebook Page:- https://www.facebook.com/UnpossibleNS

Twitter Account:- https://twitter.com/UnpossiblePOG

Blog :- https://unpossiblepog.blogspot.in/

-------------------------------

Hey guys, we shall create a code to force browser to add slash at the end of URL using HTACCESS and PHP.


Make sure to use INCOGNITO mode while implementing this because sometimes the HTACCESS code remains in a cookies which won’t help to run the updated code of HTACCESS.


Currently in folder, we have some PHP files, each file contains some text.


And we have the REWRITE RULE in HTACCESS file which will allow you to run the file without using the “.php” extension. And the rule contains an ending slash in first parameter.

So if you enter the URL without extension and end with slash, it will run that page.

But if you remove the ending slash, it will give you a 404 error. The best solution is to forcefully add ending slash in URL using the code.

So in HTACCESS, write the following code, code link is given in the description.

Notice that this file is inside the “tutorial” folder which is inside HTDOCS folder of xampp.

You have to add the URL accordingly.

So I have already created an error.php page which will forcefully add slash. Code is given in the description.

Our strategy is to send the current URL as a request parameter when error occurs.

And as you can see, it redirects and ends with slash.

So that is it, thanks for watching. Like share and subscribe.


2 comments: