Apache开启伪静态

深度链接 / 2023-12-06 21:48:36 / 201

Apache如何开启url重写?

1、编辑apache配置目录中的httpd.conf

使用yum安装apache,配置文件httpd.con在/etc/httpd/conf目录下

[root@wrx ~]# cd /etc/httpd/conf
[root@wrx conf]# pwd
/etc/httpd/conf
[root@wrx conf]# ls
extra  httpd.conf  magic

编辑httpd.conf
[root@wrx conf]# vim httpd.conf
输入
/mod_rewrite.so
查找

开启域名重写模块

将LoadModule rewrite_module moduled/mod_rewrite.so前面的#号去除,如果没有找到此行则添加一行

LoadModule rewrite_module moduled/mod_rewrite.so

将AllowOverride none改成AllowOverride all使Apache支持.htaccess

<Directory "/var/www/html/">
        Options -Indexes FollowSymLinks
        AllowOverride none
        Order Allow,Deny 
        Allow from all 
</Directory>

注:/var/www/html/ 为DocumentRoot【根目录】

<Directory "/var/www/html/">
        Options -Indexes FollowSymLinks
        AllowOverride all
        Order Allow,Deny 
        Allow from all 
</Directory>


修改完后记得重启Apache服务器

[root@wrx ~]# service restart httpd


2、在需要开启伪静态的项目根目录新建.htaccess文件

如果是在window下无法直接创建.htaccess文件可以打开命令行程序(同时按下window+R打开运行对话框,在对话框中输入cmd可以打开命令行程序)按如下操作

C:\Users\WRX>d:
D:\>echo a > .htaccess
D:\>dir
 驱动器 D 中的卷是 Data
 卷的序列号是 1876-1C51

 D:\ 的目录
2017/06/09  21:00                 4 .htaccess

可以在D盘根目录下看到.htaccess文件,此时就可以使用文本编辑器打开编辑


在 .htaccess 文件中输入内容

RewriteEngine on
RewriteRule index.html$ index.php
RewriteRule index-([1-9]+[0-9]*).html$ index.php?p=$1
RewriteRule ([a-z]{1,})-([0-9]{1,}).html$ index.php?action=$1&id=$2

注释:

RewriteEngine   为重写引擎开关,on为开启,off为关闭。

RewriteRule     是路由转向规则,$ 之前路径为浏览器中要输入路径,这里可以用正则表达式表达。$+空格 后路径为后台实际转向路径,

转向后台实际路径时可以传参数,例子里的后台页面可以用$_GET['p']   $_GET['action']  $_GET['id'] 来接收

$1 代表浏览器路径中输入的第一个正则表达式的值,以此类推,$2代表第二个正则表达式的值

RewriteRule 路由转向规则里正则表达式用括号 () 括起来