【发布时间】:2021-10-11 13:22:20
【问题描述】:
我有一个 Linux 机器上的共享主机计划,我上传了我的静态网站,其文件结构如下:
public_html/
--index.html
--style.css
--HTML/
--webpage.html
--CSS/
--JS/
--MEDIA/
现在我希望访问者可以在地址栏中输入:example.com/webpage 并能够访问实际存储在 example.com/HTML/webpage.html 中的内容。
我阅读了有关 Apache mod_rewrite 的文档以及关于 SO 和其他人的许多线程,但我无法弄清楚为什么我的 .htaccess 规则不起作用。我确信我还没有正确理解它是如何工作的 url 的路由和重定向,所以我可能犯了一些我看不到的错误。
这是我最后一次尝试将example.com/dir/webpage.html 作为example.com/webpage 服务:
RewriteCond %{DOCUMENT_ROOT}/$1 !-f
RewriteCond %{HTTP_HOST} ^(example.com)$
RewriteRule ^/?(HTML)/(.+)\-?(.+)?(.*)?$ %1/$2 [PT]
在这里,我只是尝试将introduction page of mod_rewrite 中提供的示例应用于我的案例:
我也尝试了很多其他的东西,但没有任何效果。 这么说来,我自己也可以做其他的事情,但尤其是这一件,我真的想不通。如果有人可以帮助我,我将不胜感激。
这是我的 .htaccess 文件,其中 cmets 解释了我在做什么,一切正常。
# redirect all www and http traffic to https not-www
<If "%{HTTP_HOST} == 'www.example.com' || %{REQUEST_SCHEME} != 'https'">
Redirect permanent "/" "https://example.com"
</If>
# defining cache settings for static assets
<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault M29030400
<FilesMatch "\.(webp|mp4|jpg|jpeg|png|svg+xml|webm|pdf)$">
ExpiresDefault M29030400
Header append Cache-Control "public"
</FilesMatch>
ExpiresByType text/html M3600
ExpiresByType text/css M3600
ExpiresByType text/javascript M3600
ExpiresByType text/plain M3600
</ifModule>
# what to show when resource is missing
ErrorDocument 404 /HTML/404.html
# block requests to files :
<Files ".user.ini">
Require all denied
</Files>
<Files ".htaccess">
Require all denied
</Files>
<Files "php.ini">
Require all denied
</Files>
<Files "error_log">
Require all denied
</Files>
# enable option to rewrite URLs and display them to something nicer
Options +FollowSymLinks -MultiViews
#Start the engine rewriting
RewriteEngine on
# Prevent hotlinking
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com/?(.*)?$ [NC]
RewriteRule .*\.(jpg|jpeg|gif|png|bmp|mp4|webp|svg)$ - [F,NC]
# redirect permanently example.com/index.html to example.com
RewriteRule ^index(.*)?$ / [L,R=301]
# the following is code I found on SO to strip html tags
# Remove .html (or htm) from visible URL (permanent redirect)
RewriteCond %{REQUEST_URI} ^/(.+)\.html?$ [NC]
RewriteRule - /%1 [L,R=301]
# Quietly point back to the HTML file (temporary/undefined redirect):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule - %{REQUEST_URI}.html [END]
【问题讨论】:
标签: regex apache .htaccess mod-rewrite hosting