Sinatra 静态页面
Sinatra Static Page
在我的 public 文件夹中,我有一个文件 index.html。我希望能够只使用 url localhost:4567 来显示页面(不显示 localhost:4567/index.html)
这是我当前的 ruby 脚本:
require 'sinatra'
set :public_folder, 'public'
get '/' do
redirect '/index.html'
end
我已经尝试删除重定向语句,但 url 仍然出现 index.html.
重定向背后的想法就是强制浏览器向您重定向到的位置发出新请求。
由于您不想更改 url,因此您有两种可能的解决方案:
重写而不是重定向。 Sinatra 本身不提供这样的功能,但是你可以很容易地使用一个机架中间件:
require 'rack/rewrite'
use Rack::Rewrite do
rewrite '/', '/index.html'
end
在询问根路径时提供index.html内容:
get '/' do
File.read("#{APP_ROOT}/public/index.html")
end
您可以在此处使用 send_file
:
get "/" do
send_file 'public/index.html'
end
您需要提供文件从工作目录的完整路径(即不只是 public
下的路径),并且这仅适用于根目录 url,它不会通常为目录提供 index.html
页。如果你想要,你可能需要在 Sinatra 前面设置一个单独的 Web 服务器并适当地配置它。
在我的 public 文件夹中,我有一个文件 index.html。我希望能够只使用 url localhost:4567 来显示页面(不显示 localhost:4567/index.html)
这是我当前的 ruby 脚本:
require 'sinatra'
set :public_folder, 'public'
get '/' do
redirect '/index.html'
end
我已经尝试删除重定向语句,但 url 仍然出现 index.html.
重定向背后的想法就是强制浏览器向您重定向到的位置发出新请求。 由于您不想更改 url,因此您有两种可能的解决方案:
重写而不是重定向。 Sinatra 本身不提供这样的功能,但是你可以很容易地使用一个机架中间件:
require 'rack/rewrite' use Rack::Rewrite do rewrite '/', '/index.html' end
在询问根路径时提供index.html内容:
get '/' do File.read("#{APP_ROOT}/public/index.html") end
您可以在此处使用 send_file
:
get "/" do
send_file 'public/index.html'
end
您需要提供文件从工作目录的完整路径(即不只是 public
下的路径),并且这仅适用于根目录 url,它不会通常为目录提供 index.html
页。如果你想要,你可能需要在 Sinatra 前面设置一个单独的 Web 服务器并适当地配置它。