如何在Apache httpd中将请求重定向到子目录url到root?

7bsow1i6  于 2023-03-30  发布在  Apache
关注(0)|答案(1)|浏览(100)

我有Apache httpd服务器运行在我的linux箱与ssl启用使用letsencrypt. html文件的根目录是/var/www/html.让我显示的结构/var/www/html如下;

-html
  |_ index.php
  |_ file1.php
  |_ dir1
  |  |_ index.php
  |_ dir2
     |_ index.php

我能够使用https://example.com URL访问网站。我试图实现的是,如果用户尝试访问https://example.com/dir3(不存在),根目录的index.php文件应该被传递。或者,如果用户尝试访问https://example.com/dir3/file1.php,根目录的file1.php文件应该被传递。
我尝试在/etc/httpd/conf.d/vhost-le-ssl.conf中编辑虚拟主机,但显示文件未找到。让我在下面描述vhost-le-ssl.conf;

<IfModule mod_ssl.c>
<VirtualHost *:443>
  ServerName example.com

  ServerAlias www.example.com

  DocumentRoot /var/www/html

  ServerAdmin info@example.com

  Alias /dir3 "/var/www/html"

  <Directory /var/www/html>
    AllowOverride None
  </Directory>

RewriteEngine on

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/$
RewriteRule dir3/* /var/www/html [R=301]

Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>
</IfModule>

有人可以请如何解决这个问题吗?提前感谢。

ux6nzvsh

ux6nzvsh1#

由于dir3,即“不需要的”目录是已知的,因此存在两种明显的可能性。

1. SymLink文件夹。

创建符号链接

ln -s '.' '/var/www/html/dir3'

将使文件夹存在,但显示/的内容。这有一些含义:

  • 递归,因为dir3本身将再次变得可见。
  • 如果/index. html包含依赖于其原始位置的引用,则这些引用可能会失败,具体取决于详细信息。

2.重写规则

另一种可能性是使用重写规则。
文件:/var/www/html/.htaccess

RewriteEngine On
RewriteBase "/"
RewriteCond "%{REQUEST_URI}" "^(/dir3)(/.*)"
RewriteRule ".*" "%2" [R=301,NC,L]

R=301告诉发送永久重定向信号:

  • 重写的位置将在地址栏中可见
  • 搜索引擎将学习新地址作为旧地址的继承者(保持SEO)这在从旧结构迁移到新结构时很有用。
备选:

如果您希望隐藏重定向,不被访问者和搜索引擎发现,只需省略R=301,即可:
File:/var/www/html/.htaccess

RewriteEngine On
RewriteBase "/"
RewriteCond "%{REQUEST_URI}" "^(/dir3)(/.*)"
RewriteRule ".*" "%2" [NC,L]
当服务器配置优先时:

如果您可以编辑Apache的conf-files,并且希望禁用.htaccess-files,则可以通过定义规则应用的文件夹来配置规则:
文件:httpd.confyourVirtualHost.conf

<Directory /var/www/html>
    RewriteEngine On
    RewriteBase "/"
    RewriteCond "%{REQUEST_URI}" "^(/dir3)(/.*)"
    RewriteRule ".*" "%2" [R=301,NC,L]
</Directory>

相关问题