本文主要是記錄一下在apache二級目錄上面部署react和vue項目。根目錄下面部署很簡單,可是在二級目錄下就須要在webpack的配置或者vue-cli的配置文件以及路由組件作一些簡單調整。因爲mac系統本身帶了apache,因此咱們只須要開啓就能夠了。javascript
在終端中輸入sudo apachectl start
,而後在瀏覽器中輸入"http://localhost",若是出現"It works!"則說明apache啓動成功。css
因爲mac系統在當前用戶目錄下面已經有一個Sites
目錄,專門用來存放站點的文件,這裏只須要在裏面建目錄就能夠了,這裏有兩個項目,一個爲react項目,另外一個爲vue項目,目錄以下:html
|- Sites | - react # react項目build後的目錄 | - vue # vue項目build後的目錄
在終端中進入目錄/etc/apache2
,若是是第一次配置apache,必定要把"httpd.conf"文件和目錄"extra"做個備份。接下就是編輯"httpd.conf"文件,能夠選擇把整個"apache2"目錄拖到文本編輯中進行修改,也可使用vim來編輯,記得使用root權限。vue
在配置文件中找到#ServerName localhost:80
去掉"#"號,而後找到#LoadModule rewrite_module libexec/apache2/mod_rewrite.so
一樣去掉"#"號,而後在httpd.conf
同級目錄新建一個目錄users
來放置本身的配置文件,這裏須要在apace配置中添加Include /private/etc/apache2/users/*.conf
來加載本身的配置。java
在users
目錄中新建一個文件,這裏取名叫www.example.conf
。在裏面添加內容:react
<VirtualHost *:80> DocumentRoot /Users/你的用戶名/Sites/ <Directory "/Users/你的用戶名/Sites/"> Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all Require all granted </Directory> </VirtualHost>
上面配置中的東西我就不做解釋了,由於我也不是很清楚。須要清楚的是DocumentRootxxx
和<Directory "xxx">
均指向你的網站部署所在目錄。webpack
配置好了記得重啓apache,我這裏是使用命令sudo apachectl -k restart
。web
項目是經過vue-cli 3.x生成的,在根目錄新建配置文件"vue.config.js",而後添加如下內容:vue-cli
// vue.config.js module.exports = { baseUrl: process.env.NODE_ENV === 'production' ? '/vue' : '/', outputDir: 'build', };
這裏把outputDir
改爲"build"是爲了和react保持一致。而後找到"router.js"文件,添加一個base配置。shell
注意: 怎麼把vue項目部署在二級目錄,官網文檔是有說明的。
export default new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', name: 'home', component: Home } })
最後咱們還須要在public
目錄中添加一個.htaccess
文件來配置將全部的請求轉發到靜態文件index.html
RewriteEngine On RewriteCond %{REQUEST_URI} !^/index.html$ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !\.(css|gif|ico|jpg|js|png|swf|txt|svg|woff|ttf|eot)$ RewriteRule . /vue/index.html [L]
這樣在vue這邊的準備工做就ok了。
React項目是經過create-react-app建立的,這裏只須要在package.json
中添加"homepage": "."
,這裏的homepage
值也能夠指定一個具體的域名,好比"homepage": "http://www.example.com/react"
。
而後是修改路由的basename
值。這裏使用的是"react-router 4"。
import {BrowserRouter as Router} from 'react-router-dom'; function Routes() { const isProd = process.env.REACT_APP_ENV === 'production'; return ( <Router basename={isProd ? '/react' : '/'}> </Router> ) }
而後public目錄一樣添加.htaccess
文件
RewriteEngine On RewriteCond %{REQUEST_URI} !^/index.html$ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !\.(css|gif|ico|jpg|js|png|swf|txt|svg|woff|ttf|eot)$ RewriteRule . index.html [L]
在瀏覽器中打開地址http://localhost/react
便可查看react項目,http://localhost/vue
來查看vue項目。本人電腦上親測是沒有問題的,訪問路由http://localhost/vue/about
都ok的。這裏只是一個簡單的記錄,沒有作過多的說明。