因为要写一个YII2.0+vue的前后端分离的项目,要用到yii2.0提供接口,所以就需要配置.htaccess文件。
直接贴上我的代码:
Options +FollowSymLinks IndexIgnore */* RewriteEngine on #这边开始准备允许跨域请求 #指定了该响应的资源是否被允许与给定的origin共享 Header always set Access-Control-Allow-Origin "*" #指定访问资源的方式 Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT, PATCH, HEAD" #是否可以将对请求的响应暴露给页面(false不允许) Header always set Access-Control-Allow-Credentials "false" #列出了将会在正式请求的 Access-Control-Expose-Headers 字段中出现的头部信息 Header always set Access-Control-Allow-Headers "Authorization,DNT,User-Agent,Keep-Alive,Content-Type,accept,origin,X-Requested-With" RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=200,L] # if a directory or a file exists, use it directly #如果文件存在,就直接访问文件,不进行下面的RewriteRule.(不是文件或文件不存在就执行重写) RewriteCond %{REQUEST_FILENAME} !-f #如果目录存在就直接访问目录不进行RewriteRule RewriteCond %{REQUEST_FILENAME} !-d # otherwise forward it to index.php RewriteRule . index.php RewriteRule \.svn\/ /404.html RewriteRule \.git\/ /404.html 以上是我的配置,因为考虑到跨域问题所以加了相应的配置。 只有以上的.htaccess文件是不够的的,apache需要开启以下的模块(很重要): LoadModule rewrite_module modules/mod_rewrite.so LoadModule headers_module modules/mod_headers.so 在httpd.conf配置里把权限开到最大: AllowOverride None改为AllowOverride All 这时候如果还是报错,找到apache配置文件httpd.conf里的ErrorLog,查看错误日志,这里的报错信息比页面要详细(集成环境直接在安装目录apache下bin目录里找到error.log),根据报错来定位问题。例如我的LoadModule headers_module modules/mod_headers.so模块没有开启,错误日志会记录: Invalid command 'Header', perhaps misspelled or defined by a module not included in the server configuration 另外附上我查找的资料: Apache中RewriteCond规则参数的详细介绍 https://www.cnblogs.com/yuanlipu/p/5931729.html htaccess文件中RewriteRule 规则参数介绍 https://www.cnblogs.com/beyang/p/7357787.html HTTP-headers各参数的详细介绍 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers