Home > Backend Development > PHP Tutorial > How to Remove .php and .html Extensions from URLs Using NGINX?

How to Remove .php and .html Extensions from URLs Using NGINX?

Patricia Arquette
Release: 2024-11-16 19:42:03
Original
1025 people have browsed it

How to Remove .php and .html Extensions from URLs Using NGINX?

How to Remove Both .php and .html Extensions from URLs Using NGINX

Introduction

When serving web content, it can be desirable to hide file extensions from the URL for aesthetic or security reasons. This can be achieved using NGINX, a popular web server software.

Problem

The goal is to remove both .php and .html extensions from URLs while maintaining their functionality. For example, the URL http://www.mydomain.com/indexhtml.html should be displayed as http://www.mydomain.com/indexhtml, and http://www.mydomain.com/indexphp.php should be displayed as http://www.mydomain.com/indexphp.

Solution

The following NGINX configuration can be used to achieve the desired result:

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

location ~ \.php$ {
    try_files $uri =404;
}

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

Explanation

  • location /: This block applies to all requests to the website's root directory.
  • try_files: This directive tries to find the file specified by $uri. If the file doesn't exist, it tries to find $uri.html or a directory of the same name. If neither exists, it will pass the request to the @extensionless-php location block.
  • index: This directive specifies the default files to serve when $uri points to a directory.
  • location ~ .php$: This block matches requests ending in .php.
  • try_files $uri =404: This directive returns a 404 error if the URI is exactly a .php file (excluding directories).
  • location @extensionless-php: This block is where the rewiring happens.
  • rewrite: This directive rewrites the request to the URI with the .php extension added. The last flag prevents further rewriting.

By implementing this configuration, both .php and .html extensions will be automatically removed from URLs, providing a clean and user-friendly browsing experience.

The above is the detailed content of How to Remove .php and .html Extensions from URLs Using NGINX?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template