【问题标题】:How do I enable url rewriting?如何启用 url 重写?
【发布时间】:2014-09-09 12:48:45
【问题描述】:

我正在使用 Debian Jessie。我想启用 URL 重写。很多网站,比如this blog,建议我编辑

/etc/apache2/sites-available/default

但是,没有这样的文件,但它包含000-default.conf,其中包含以下代码:

<VirtualHost *:80> 
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

没有包含的行

AllowOverride None

我可以用上面指定的博文中给出的代码覆盖这个文件吗?

之后,我可以在我的 /var/www/html/somesite/ 文件夹中使用以下代码放置一个 .htaccess 文件

RewriteEngine On
RewriteRule  ^this/page/thispage this.php?page=thispage

用“this/page/thispage/”覆盖“this.php?page=thispage”?

并且(额外的问题),有没有办法覆盖所有的 GET 请求,所以任何形式为“this.php?variable1=foo&variable2=bar”的链接都会导致形式为“this/variable1/foo/variable2 /bar”?

【问题讨论】:

    标签: .htaccess mod-rewrite apache2 debian


    【解决方案1】:

    首先你需要在你的机器上启用重写模块:

    a2enmod rewrite

    如果未安装,请执行以下操作:

    apt-get install rewrite

    然后编辑您的虚拟主机区域:

    Allow from all AllowOverride All

    如果你还没有创建你的虚拟主机文件,你可以从默认复制它:

    cd /etc/apache2/sites-available

    cp 000-default yourwebsite.com

    为新网站创建 vhost 文件后,启用它:

    a2ensite yourwebsite.com

    最后,您需要将.htaccess 文件放在文档根目录中

    【讨论】:

      【解决方案2】:

      你需要添加:

      <Directory "/var/www/html">
          Allow from all
          AllowOverride All
      </Directory>
      

      在你的虚拟主机中

      您的 htaccess 文件需要进入文档根目录,即/var/www/html

      那么你可以这样做:

      Options -Multiviews
      RewriteEngine On
      RewriteRule  ^this/([^/]+)/([^/]+)$ this.php?$1=$2 [L]
      RewriteRule  ^this/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ this.php?$1=$2&$3=$4 [L]
      

      这将使得 当你在浏览器中输入这个 URL 时http://example.com/this/a/b/c/d,你会看到页面 /this.php?a=b&amp;c=d,并且 URL 不会改变。

      【讨论】:

      • 谢谢,还有一个问题。我的虚拟主机到底是什么?我应该设置一个新的虚拟主机,还是可以使用 000-default.conf。 (请注意,我的文档根目录上有多个项目)
      • @Yatoom "vhost" = "虚拟主机"。视情况而定,如果请求与来自任何其他虚拟主机的ServerNameServerAlias 不匹配,“默认”是将使用的虚拟主机。如果您计划托管很多站点,您可能希望为每个站点设置特定的虚拟主机,但如果您只有 1 个站点,则使用默认值即可。
      猜你喜欢
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 2013-01-08
      • 2016-11-28
      • 1970-01-01
      • 2016-10-30
      相关资源
      最近更新 更多