php - 没有 .htaccess 的 Mod 重写

标签 php apache .htaccess mod-rewrite vhosts

假设我有一个名为

的网站
foo.com

我可以访问 foo.com 并且它运行在根文件夹中找到的 index.php。我的问题是:我应该如何编辑 vhost 文件以启用重写模式而不启用 htaccess?

我的目标是能够写作

http://foo.com/bar/loremipsum/dolor

进入我的浏览器地址栏并运行index.php,无论网址中的/字符数量如何。我的index.php将处理由/分隔的参数

我怎样才能实现这个目标?

编辑: 虚拟主机文件:

<VirtualHost *:80>
        ServerName myproject.com
        ServerAlias www.myproject.com

        ServerAdmin webmaster@localhost
        DocumentRoot /opt/apps/myproject

        <Directory /opt/apps/myproject>
            # disable htaccess
            AllowOverride None

            # route everything to index.php
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteRule ^ /index.php [L]

            Require all granted
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

编辑:正如所接受的答案所表明的那样,问题是该主机不包含打开重写引擎的行。该行出现在答案中。这解决了问题。

最佳答案

要禁止使用 htaccess,您需要在 <Directory> 中使用此指令文档根目录的容器,那么您可以将 mod_rewrite 规则放在同一个容器中:

<Directory "/var/www/htdocs/">
    # disable htaccess
    AllowOverride None

    # route everything to index.php
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ /index.php [L]
</Directory>

假设“/var/www/htdocs”是您的文档根目录。

要确保 mod_rewrite 已加载,请检查 httpd.conf 文件中的 LoadModule包含 mod_rewrite 的行,并确保它未被注释。每当更改虚拟主机配置时,您都需要重新启动服务器。

简短说明:

行:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

是检查请求不是现有文件 ( -f ) 或现有目录 ( -d ) 的条件。这些条件有两个主要目的:

  1. 它可以防止重写引擎循环,因此index.php也不会被重写。自 index.php是现有文件,条件将停止重写引擎。
  2. 它允许重写图像或脚本等资源和 Assets 。

如果您希望将所有内容路由到 index.php无论什么(包括图像或其他任何内容),您都可以将这 2 个条件更改为:

RewriteCond %{REQUEST_URI} !^/index.php

这样除了 index.php 之外的所有内容都会被重写.

关于php - 没有 .htaccess 的 Mod 重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30193087/

相关文章:

wordpress - 重写到Wordpress基础之外的URL

php - 统计mysql中某一列的不同字符串

夏令时的 PHP 日期问题

php - AWS EC2 实例上的 S3-php5-curl - 请求的域名与服务器的证书不匹配

apache - 如何将包含下划线的所有 URL 更改为破折号,但仅限一个目录

java - 在 Android 中跨 http 调用维护 session

apache - 301 通过 .htaccess 将查询字符串重定向到 SEO 友好的 URL

javascript - 邮件枪 API : Request header field Authorization is not allowed by Access-Control-Allow-Headers

php - 从 Array PHP 插入表

php - 如何在.htaccess 中设置upload_max_filesize?