利用Apache重写模块(Rewrite)隐藏网页文件类型后缀

在访问网页时, 网址往往是https://example.com/index.htmlhttps://example.com/index.php, 总会带一个文件类型后缀, 代表所访问的是一个html文件或php文件, 但如果想要把这个文件类型后缀去掉, 应该怎么做呢?

如果服务端使用的是Apache, 可以使用自带的重写模块(rewrite mod)实现域名重写.

启用Apache重写模块

httpd

vim /etc/httpd/conf/httpd.conf

查找该文件是否有以下字段

LoadModule rewrite_module modules/mod_rewrite.so

若存在, 删去该字段前面的#号, 若不存在, 直接添加该字段.

随后

vim /etc/httpd/conf.modules.d/000-rewrite.conf

添加如下字段

LoadModule rewrite_module modules/mod_rewrite.so

Apache2

首先开启重写模块

a2enmod rewrite

然后验证一下配置文件有无语法错误

apache2ctl configtest

若输出

Syntax OK

再重载配置文件

systemctl reload apache2

配置重写规则

vim /var/www/html/.htaccess

输入如下字段

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

可以根据自己想要隐藏的文件类型后缀自行添加配置, 别忘了重载配置文件

systemctl reload apache2

随后在浏览器输入https://example.com/index也能够正确的访问网页了, 内容与带后缀的网址内容一样.

配置完毕后, 后端传递数据时域名也可以省略文件类型后缀, 例如表单要传输到https://example.com/query.php?q=xxx直接将url写为https://example.com/query?q=xxx也可以完成数据提交.

posted @ 2022-03-27 21:20  方清欢  阅读(338)  评论(0编辑  收藏  举报