Introduction

Many website owners prefer not to expose the programming language used to build their applications. For example, instead of accessing a page as https://example.com/about.php, it is often cleaner and more professional to use https://example.com/about.

In Apache, this can be achieved using .htaccess rules. In Nginx, the same functionality can be implemented through URL rewriting and the try_files directive.

This guide explains how to configure Nginx to automatically serve PHP files without requiring the .php extension in the URL.

Prerequisites

If Nginx is not already installed on your server, refer to the following installation guides:

  • Install Nginx, PHP, and MariaDB on Ubuntu
  • Install Nginx, PHP-FPM, and MariaDB on CentOS 7

Implementation

Open the Nginx configuration file. If you want this feature to apply only to a specific website, update the corresponding virtual host configuration instead of the default configuration.

vi /etc/nginx/sites-enabled/default

Add the following configuration inside the server block:

location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
    index index.html index.htm index.php;
}

location @extensionless-php {
    rewrite ^(.*)$ $1.php last;
}

How It Works

  • try_files checks whether the requested file or directory exists.
  • If no matching file is found, the request is passed to the @extensionless-php location.
  • The rewrite rule automatically appends the .php extension and processes the request.
  • Users can access pages without exposing the PHP extension in the URL.

Example:

Instead of:

https://example.com/contact.php

Users can access:

https://example.com/contact

Validate the Configuration

Before restarting Nginx, verify that the configuration syntax is correct:

nginx -t

A successful validation will display:

nginx: configuration file /etc/nginx/nginx.conf test is successful

Apply the Changes

Restart the Nginx service for the new configuration to take effect:

systemctl restart nginx

Conclusion

Configuring Nginx to automatically handle PHP extensions helps create cleaner, more user-friendly URLs while keeping the underlying technology hidden from visitors. This approach improves URL readability, provides a more professional appearance, and can be implemented with just a few lines of configuration.

Always test the configuration using nginx -t before restarting the service to avoid downtime caused by configuration errors.

Leave a Reply