Virtual directory redirect with Nginx and PHP

Redirect a virtual directory and adjacent url from your website with PHP and Nginx. Tested on PHP 8.0.1

Backend web development is usually a ton of GET/POST requests to servers on the internet. The URIs that manage these represent how the variables and data flows through the internet. A default link with query parameters and their values are hard to remember and can be confusing. Popular web servers like Apache/Nginx/Node provide this functionality to make URLs more user-friendly. I’m just posting an example as I took way too long to find this on my own. I was thinking it would have been easier to find but solutions I found online were incomplete.

We are going to make server take:

but use the redirect.php at the root folder to perform the redirect

As for a Nginx, you need a configuration file on the root of your application. Nginx takes this file as reference for rewrites to work. As we are going to use a virtual folder, we do not need to create one.

On the nginx.conf:

location / {
    rewrite ^/go/(.*)$ /redirect.php?url=$1 last;

The “location” in the first line represents where the configuration takes effect. The rewrite statement uses regex to separate out a virtual directory (/go/) and a selection group to be used as an URL parameter for the redirect.php file.

On the redirect.php:

if (isset($_GET['url'])){ #Checks if url parameter is set
    $url = filter_var($_GET['url'], FILTER_SANITIZE_URL); #sanitze the url
    if (filter_var($url, FILTER_VALIDATE_URL)){ #validate if the url is valid
        header('Location: '.$url); #Redirect takes place here
 #the script exits
    echo 'Nothing is set...';

And that’s about it. Place it on your nginx server running PHP and watch links from virtual folder get redirected to the links place next to it. I have tested it on PHP 8.0.1 and it works pretty well.

Leave a Reply