Asked  1 Year ago    Answers:  5   Viewed   9 times

I need to redirect my symfony website from "" to "". I have tried some solutions in stack overflow but they add multiple "www." to the address and others didn't work.

Here is my htaccess source.

DirectoryIndex app.php

<IfModule mod_negotiation.c>
    Options -MultiViews

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::2$
    RewriteRule ^(.*) - [E=BASE:%1]

    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^app.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    RewriteRule .? %{ENV:BASE}/app.php [L]

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        RedirectMatch 302 ^/$ /app.php/

How can I do this?



Add the following rule as the first rule:

RewriteCond %{HTTP_HOST} !^(www).
RewriteRule ^(.*?)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Thursday, April 1, 2021

Simply inject request_stack instead of request and call getCurrentRequest().

Saturday, May 29, 2021

You can add listener that will check if locale is set.

$kernel->getContainer()->get('event_dispatcher')->addListener(SymfonyComponentHttpKernelKernelEvents::REQUEST, function($event) {
    if ($event->getRequestType() != SymfonyComponentHttpKernelHttpKernelInterface::MASTER_REQUEST) return;

    $request = $event->getRequest();
    $locale = $request->attributes->get('_locale');
    if (!$locale) {
        // Try to get the preferred language from the request
        $locale = MySettings::getLanguage($request);
        return new SymfonyComponentHttpFoundationRedirectResponse('/' . $locale . '/' . ltrim($request->getRequestUri(), '/'));
    } elseif (!MySettings::checkLanguage($locale)) {
        // Invalid Locale...
        throw new SymfonyComponentHttpKernelExceptionNotFoundHttpException();


$response = $kernel->handle($request);
Saturday, May 29, 2021

Using the rewrite engine is a pretty heavyweight way to solve this problem. Here is a simpler solution:

<VirtualHost *:80>
    Redirect permanent /

<VirtualHost *:80>
    # real server configuration

And then you'll have another <VirtualHost> section with ServerName for your real server configuration. Apache automatically preserves anything after the / when using the Redirect directive, which is a common misconception about why this method won't work (when in fact it does).

Tuesday, June 1, 2021

Your code is not quite right. See below.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^$ [NC]
RewriteRule ^.*${REQUEST_URI} [R=301,L] # <-- Mind the 'L'!

RewriteRule ^$ webroot/    [L]
RewriteRule (.*) webroot/$1 [L]
Friday, December 10, 2021
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :