【问题标题】:Redirect http to https in .htaccess (Symfony 4)将 http 重定向到 .htaccess 中的 https (Symfony 4)
【发布时间】:2026-01-12 15:45:01
【问题描述】:

我正在尝试在共享主机 (Cpanel) 中托管我的 symfony 4 网站,并且我想自动将 http 重定向到 https。

我在这里发现很多问题是我应该更改 mu .htaccess,这是我当前的 .htaccess 内容:

DirectoryIndex index.php

AddType application/x-lsphp72 .php

<IfModule mime_module>
  AddType application/x-httpd-ea-php72 .php .php7 .phtml
</IfModule>

<IfModule mod_rewrite.c>
    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ %{ENV:BASE}/index.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        RedirectMatch 302 ^/$ /index.php/
    </IfModule>
</IfModule>

<IfModule php7_module>
   php_flag display_errors On
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit 128M
   php_value post_max_size 8M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php72"
   php_value upload_max_filesize 10M
   php_flag zlib.output_compression Off
</IfModule>
<IfModule lsapi_module>
   php_flag display_errors On
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit 128M
   php_value post_max_size 8M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php72"
   php_value upload_max_filesize 10M
   php_flag zlib.output_compression Off
</IfModule>

<IfModule mime_module>
  AddHandler application/x-httpd-ea-php72 .php .php7 .phtml
</IfModule>

我在这个问题上找到了Redirect HTTP to HTTPS 我应该添加:

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://website.com/$1 [R=301,L]

但我收到 ERR_TOO_MANY_REDIRECT 错误。

你们中有人跟我一样吗?

感谢您的帮助。

【问题讨论】:

  • 这能回答你的问题吗? Redirect HTTP to HTTPS
  • 我通过添加这个得到 ERR_TOO_MANY_REDIRECT 错误:/
  • 您尝试过什么方法来解决这个问题?
  • @NicoHaase 我试过这个:RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ website.com/$1 [R=301,L]
  • 还有这个:access_control: - { path: ^/my-path, requires_channel: https }

标签: php .htaccess symfony cpanel symfony4


【解决方案1】:

我通过security.yaml解决了这个问题

 access_control:
     - { path: ^/my-path, requires_channel: https }

现在当我自动访问http://my-website.com/my-path 时,我被重定向到 https

【讨论】:

【解决方案2】:

建议修改虚拟主机而不是.htaccess
/etc/apache2/sites-available 中的配置文件)

这样做,你就准备好了:

# Catch and redirect all http
<VirtualHost *:80>
    ServerName example.com

    Redirect / https://example.com/
</VirtualHost>

<VirtualHost _default_:443>
    ServerName example.com

    # Rest of your vhost
</VirtualHost>

【讨论】:

  • 其实/etc文件夹里面没有apache2文件夹
  • 在虚拟主机中工作是个好主意 - 但对于包含任何路径的深层链接,这应该如何工作?
  • 当前示例重定向 / 之后的所有内容。因此,如果您的网址是 http://example.com/page/1?v=2,那么它将重定向到 https://example.com/page/1?v=2
  • @AdnaneLamghari 你在使用 nginx 吗?如果是这样,则存在相同的方法,在 nginx 语法中。
  • @Preciel 不,我没有使用它:/