Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skoobi's avatar
Level 13

Strip .php from url

Hi. Is there a way to strip any .php filenames from the end of the url.

Im using Forge and Digitalocean but was wondering if theres a way to do it through middleware?

Cheers

0 likes
8 replies
dqfan2012's avatar

This depends on the technology you're using to serve your website. If you're using Apache, that can be achieved by using Rewrite rules in your Apache vhost configuration (if you have access to this configuration) or adding an .htaccess file to your webroot.

Apache Example:

RewriteRule ^category/([-\w]+)/$ category.php?url=$1 [NC,L]

This rewrite rule performs a case insensitive pattern match on the URL. If there is a match, no further rules will be processed.

It would match category.php/javascript and rewrite the URL as category/javascript

If you need to accomplish this using nginx. I recommend you do a Google Search for "clean URLs and php extension on nginx".

I hope this helps.

skoobi's avatar
Level 13

Thank guys. Im using nginx on forge. Im not going to lie but ive not used nginx before and a liitle afraid of messing with it.

But as a fix for now, I made a middleware to process the request and check for the extention and remove it then redirect to the correct location

if (str_contains($request->url(), '.php')) {
            $url = str_replace('.php', '', $request->url());
            return redirect($url);
        }
yassineqoraiche's avatar

@SKOOBI - you can use this regex to remove complex URL extension:

$withoutExt = preg_replace('/\.[^.\s]{3,4}$/', '', $filename);

skoobi's avatar
Level 13

Would that go in the

server {
$withoutExt = preg_replace('/\.[^.\s]{3,4}$/', '', $filename);
}

EDIT!!!! Sorry just clicked!!!!

Ill give that a go... Cheers

skoobi's avatar
Level 13

Sorry, Ive tried all sorts now and it fails on the Forge Digital ocean server using Nginx...

Locally it works perfect using Valet but as soon as its on the DO server i get No input file specified.

I cannot figure it out at all. Any ideas??

This is my middleware that catches all requests ::

public function handle($request, Closure $next)
    {
        if (str_contains($request->url(), '.php')) {
            $url = str_replace('.php', '', $request->url());
            return redirect($url);
        }
        return $next($request);
    }

Cheers

skoobi's avatar
skoobi
OP
Best Answer
Level 13

Ok so after a lot of digging around and learning about Nginx i found a solution...

In the nginx config file i added ::

rewrite ^/registration.php /registration permanent;

This works perfectly.

Please or to participate in this conversation.