简体   繁体   中英

Externally redirect URL in NGINX conf to add slashes and use php files

I'm new in this site and new with NGINX, so be nice, please. I rencently switched to AWS Elasticbeanstalk and need help with NGINX configuration. I wanna do some redirection that I know and tested that works in apache2 with .htaccess but I'm not able to acomplish with NGINX.

I want all my URL to end with trainling slash, check if $uri is a directory if so use index.php if not use last name as the name of the script as follows:

I want that this URL: uses this script:

https://localhost/ -> ./index.php

https://localhost/page/ -> ./page.php

https://localhost/folder/page/ -> ./folder/page.php

https://localhost/folder/page/?param=foo -> ./folder/page.php?param=foo

I made it behave like this in apache2 with this config in .htaccess:

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1/ [R,L]

# add a trailing slash   
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

How can I translate this .htaccess into NGINX config file?

Thanks in advance.

Try having this, remember to restart after insertion:

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 ^(.*)$ $1.php last;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM