Home > Software design >  How to route all URLs except some to a PHP file?
How to route all URLs except some to a PHP file?

Time:02-10

I'm working on a PHP project. I want to route all URLs except some (/, /index.php, /video-archive.php etc.) to a PHP file which is /article.php

Let me describe it in more detail:

Consider that I have article.php at URL https://example.com/article.php, when a client wants to reach to URL https://example.com/how-to-grow-beautiful-flowers.php or without the .php extension, I want this request to be processed by this https://example.com/article.php URL or simply article.php file. If user wants to reach https://example.com/ or https://example.com/index.php or https://example.com/video-archive.php they will reach to index.php and video-archive.php. So there will be exceptions to that route.

REQUEST URL                                            PROCESSING URL
https://example.com/                                   https://example.com/index.php
https://example.com/index.php                          https://example.com/index.php
https://example.com/index                              https://example.com/index.php
https://example.com/video-archive                      https://example.com/video-archive.php
https://example.com/video-archive.php                  https://example.com/video-archive.php
https://example.com/how-to-grow-flowers                https://example.com/article.php
https://example.com/types-of-flowers                   https://example.com/article.php
https://example.com/about-us                           https://example.com/article.php

NOTE: I'm currently developing this project using XAMPP on my computer (localhost). But I'm planning to deploy it on a server in future. So it should be better to consider this information.

CodePudding user response:

You can redirect all requests to /article.php expect requests to files that actually exist. Example requests to /index.php, /video-archive.php and static files will load the actual file. Try this

Put this in a .htaccess in the root directory

RewriteEngine On

# redirect all request to article.php except existing files
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ article.php [QSA,L]

You can then get the URI in the article.php file like so

$article_url = rtrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '.php');
// when a client hits https://example.com/how-to-grow-beautiful-flowers.php
// $article_url equals '/how-to-grow-beautiful-flowers'
  • Related