.htaccess-从子目录重定向到不存在文件的根目录 [英] .htaccess - redirect from subdirectory to root directory for non existing files

查看:91
本文介绍了.htaccess-从子目录重定向到不存在文件的根目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前目录结构:

wwwpublic
|+ spanish(language)
|-- index.php
|-- contact.php
|
|- index.php
|- aboutus.php
|- products.php
|- contact.php

在wwwpublic目录的根目录中,我有英语文件。由于网站也使用西班牙语,因此我创建了单独的目录 spanish。这两个目录中的页面名称完全相同。

In the root of wwwpublic directory I have files in the English language. Since site have Spanish language too, I have created separate directory named 'spanish'. Name of pages are exactly the same in both directories.

现在,西班牙目录中的某些页面不存在,我需要将对此类页面的请求重定向到根文件夹,保留请求的文件名。

Now, some pages in spanish directory don't exist and I need to redirect request to such pages to root folder and retain name of file requested.

示例:
访客转到西班牙语版本,在此处打开index.php,然后单击aboutus.php页面(不存在) )在西班牙目录中,然后.htaccess将他重定向到/root/aboutus.php

Example: Visitor go to Spanish version, open index.php there, then he clicks on aboutus.php page (dont exists) inside spanish directory and then .htaccess redirects him to the /root/aboutus.php

推荐答案

在您的 wwwpublic 目录,最好在您可能具有任何路由规则之前:

Try something like this in your wwwpublic directory, preferably before any routing rules you may have:

RewriteEngine On

# conditions to check that current request doesn't point to a valid resource
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# condition to check that request is for the /spanish/ directory
RewriteCond %{REQUEST_URI} ^/spanish/(.+)$

# conditions to check if the /spanish/ is removed whether it would point to a valid resource
RewriteCond %{DOCUMENT_ROOT}/%1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/%1 -d

# all conditions match, rewrite
RewriteRule ^/?spanish/(.+)$ /$1 [L]

这篇关于.htaccess-从子目录重定向到不存在文件的根目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆