Hello,
Help please to make work both rules with and without (php and html) prefix from url in nginx/fpm
I add this rules in web server configuration in control panel:
if (!-e $request_filename){
rewrite ^/([^\.]+)$ /$1.php break;
}
if (!-e $request_filename){
rewrite ^/([^\.]+)$ /$1.html break;
}
But work only first. The second rule is ignored, how to combine them. Thank you.
@oim37
There are some golden Nginx rules, two of them being :
1 - IF is EVIL : one should not use if statements, if not necessary
2 - keep it simple : this golden rule simply implies that rewrites and redirects, certainly in the same location block, are often not necessary at all!
It is clear that
@scsa20 has given you a solution that is too some extent or even a high degree compliant with the aforementioned golden rules.
However, you probably can suffice by simply using the line
try_files $uri $uri.html $uri/ =404;
and you should test that first.
If that line works for requests ending with and without .html at the end, then you are ready to augment the line to
try_files $uri $uri.php $uri.html $uri/ =404;
and that one particular line should - in theory - allow you to achieve your goals.
That one particular line simply tells Nginx
- first try $uri
- then try $uri.php
- then try $uri.html ........ at this point, you have achieved your objectives already (!)
- then try $uri/ ........ just a proper addition, for the sake of certainty
- only after trying the first options, only then return the 404 code
If this particular line is not sufficient to achieve your goals and does not work with the code that Nginx is proxying for, then that code is requiring more specific Nginx config - this should (normally) not be the case!
As a final note, please note that your goals and objectives are essentially (also) dealing with requests that do not include parameters that are often quite common and/or that can be required.
That is, parameters such as .php?test=123 or .html?test=123....
If you need those parameters in order to have underlying code working properly, then the line proposed by me could still be sufficient, but you should be aware of the fact that some requests to Nginx are not including the parameters .........
............. and this is not often desirable (read: when having code that wants those parameters as input)
............. but sometimes it can be highly desirable (read: when trying to make requests more secure and less vulnerable to parameter injection)
I hope the above helps a bit!
Kind regards.....