Reputation: 104
I have a website I need to move from an Apache server to an Nginx server.
The .htaccess file of this website is as follows
RewriteEngine on
RewriteRule ^([^/\.]+)/?$ $1.php [L]
This redirects www.example.com/hello to www.example.com/hello.php keeping the original link, but omiting the .php from the end of the url.
I tried to replicate this in my Nginx server block..
location / {
# Check if a file exists, or route it to index.php.
try_files $uri $uri/ /index.php;
}
rewrite ^/([a-z]+)$ /$1.php last;
The rewrite rule works, redirecting all links to the .php file, but breaks the Nginx try_files rule for searching inside a directory if the file does not exist.
The below admin example link is a folder with an index.php file inside it.
www.example.com/admin
The try_files should redirect this to..
www.example.com/admin/
Since there is no file called admin.php. Instead I get the 'No input file specified' message.
When I remove the rewrite, the try_files works correctly. However the rest of the site does not work without this rewrite rule.
Does anyone know how I can get the try_files and the rewrite to work together?
Thanks
Ben
Upvotes: 3
Views: 2206
Reputation: 54
You can set the index to be index.php in either the location directive or the server
index index.php index.html;
And requests going to /admin/index.php for example will show up as /admin/
OR Having try_files try to put .php at the end of the request
location / {
try_files $uri $uri.php =404;
}
In this your /admin wouldn't be a folder instead it is admin.php but it gets tricky if you also have a folder named /admin/ as it would try /admin.php and /admin/index.php
Upvotes: 0
Reputation: 103
I know this may not help, but I look at your use case and I have to wonder how do you know that a request for /admin should go to /admin/ and not /admin.php?
I mean your rewrite rule clearly states that if you receive a request for /[a-z]+ then it should be rewritten to /[a-z]+.php
Yet you want a try_files to push /admin to /admin/ instead?
Looking at your apache rule:
RewriteRule ^([^/\.]+)/?$ $1.php [L]
I see here that you're trying to limit what gets sent to x.php. I don't see any such restrictions in your nginx rewrite.
Upvotes: 0