bnoeafk
bnoeafk

Reputation: 539

Call to PHP page served by nginx without using the file extension

I'm sure this is a really simple answer, but I just can't seem to crack it. I'm also quite new to nginx, but quite knowledgeable with apache2. I'm running nginx on Ubuntu and trying to fulfill these two requests:

  1. get nginx to serve filename.php when the URI calls for filename
    1. Calling http://example.org/bob would serve http://example.org/bob.php but still http://example.org/bob is shown in the browser URL
  2. when a folder is requested, "index" isn't shown in the URL
    1. Calling http://example.org/jack/ would serve http://example.org/jack/index.php but http://example.org/jack/ is still shown in the URL (and not http://example.org/jack/index)

My current config is:

server {
    listen 80;
    root /var/www/html;
    index index.php;

    location / {
        try_files $uri $uri/ @php;
    }

    location @php {
        try_files $uri.php =404;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi.conf;
    }

    rewrite ^/(.*)\.php$ /$1 redirect;

    location ~ /\.ht {
        deny all;
    }
}

I feel as if I'm really close, requirement (1) works flawlessly, but I can't seem to find the correct config to address requirement (2).

If it helps, this is the config that works in Apache2, with the mod_rewrite module enabled:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d       # if a folder isn't called ...
RewriteCond %{REQUEST_FILENAME}.php -f    # but a php file is ...
RewriteRule ^(.*)$ $1.php                 # take the basename, add .php then call that

Upvotes: 3

Views: 907

Answers (1)

Avinash Dalvi
Avinash Dalvi

Reputation: 9301

See this can help you to enable Apache2 rewrite rule to nginx rules :

https://www.nginx.com/blog/converting-apache-to-nginx-rewrite-rules/

location / {
  if (!-e $request_filename){
    rewrite ^(.*)$ /$1.php;
  }
}

Upvotes: 2

Related Questions