问题
i have an issue with url rewriting in nginx server. i want to hide symfony's locale from my url so www.example.com/fr/route should be www.example.com/route my nginx config file has the following :
location / {
# try to serve file directly, fallback to app.php
try_files $uri /app.php$is_args$args;
}
# PROD
location ~ ^/app\.php(/|$) {
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
internal;
}
please help me and thanks a lot in advance.
i already try with .htaccess but nginx doesn't support .htaccess files
回答1:
Hello there and welcome to the forum.
As you have tagged your question with url-rewriting, I am assuming that you want to achieve url rewriting instead of something else. i.e. url rewriting isn't "hiding" that part of the url, it is rewriting the url and removing that part - meaning that this information won't be available to you in your symfony project.
The following nginx rule will do the url-rewriting:
rewrite ^/fr/(.*)$ /$1 permanent;
please note that it might be a good idea in general to use non-permanent option when testing/creating these rules like this:
rewrite ^/fr/(.*)$ /$1 redirect;
updated regarding how to "hide" the locale
This is something that you would have to do inside your symfony project instead of using nginx. As a warning though, symfony documentation explicitly advises against using this kind of locale hiding (see The locale and the url). But if you for some reason still want to do this kind of locale hiding, I would assume one approach would be to create generic catcher routes for handling your locales - something like this:
locale_redirect:
path: /{_locale}/{params}
controller: App\Controller\LocaleRedirectController::locale
requirements:
_locale: en|fr|de
params: '.+'
And in you controller something like this:
public function localeAction(Request $request, $locale, $params)
{
// set the locale sticky
// https://symfony.com/doc/current/session/locale_sticky_session.html
// redirect to the url without the locale
return new RedirectResponse("/$params");
}
I haven't actually tried this code / logic - and wouldn't do this because symfony documentation advises against it (for valid reasons) - so there might be some small issues with this example code / this logic that you need to figure out for yourself if you decide to go this way.
来源:https://stackoverflow.com/questions/53481951/nginx-hide-symfony-locale-from-url