当用户输入http://example.com时,我想将其重定向到http://www.example.com。
如果我使用nginx + php,我可以使用下面的
server {
listen 80;
server_name example.com;
return 301 http://www.example.com$request_uri;
}
server {
server_name www.example.com;
root /var/www/html/example.com;
index index.php index.html index.htm;
location / {
index index.php index.html index.htm;
try_files $uri $uri/ /index.php$is_args$args;
}
// skip some non related config
}
但是如果我使用react JS
那该怎么办? $ sudo npm start
和webpack.dev.config.js
var webpack = require("webpack");
var path = require("path");
var parentDir = path.join(__dirname, "../");
module.exports = {
entry: [path.join(parentDir, "index.js")],
module: {
loaders: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
}
]
},
output: {
path: parentDir + "/dist",
filename: "bundle.js"
},
devServer: {
contentBase: parentDir,
historyApiFallback: true,
host: "0.0.0.0",
disableHostCheck: true
}
};
loaders: [{ test: /\.css$/, loader: "style-loader!css-loader" }];
我可以达到同样的目的吗?我想在服务器端重定向它们,但不是客户端。谢谢!
答案 0 :(得分:1)
使用window.location
对象检查当前主机名,如果不是以 www
if (!window.location.host.startsWith("www")){
window.location = window.location.protocol + "//" + "www." + window.location.host + window.location.pathname;
}