开发者

How do I use rack-rewrite to remove .html (if the file exists)?

开发者 https://www.devze.com 2023-03-28 17:37 出处:网络
I\'m not a Rubyist, but I do rather like Jekyll and the ease of which I can spin up a \"blog enabled\" site in combination with Heroku and Git.

I'm not a Rubyist, but I do rather like Jekyll and the ease of which I can spin up a "blog enabled" site in combination with Heroku and Git.

I'm wanting to use Rack-Rewrite (or if there is something better to do the same, I'm happy to use that) to have '/foo' rewritten to '/foo.html' (ie, appending the .html but not changing the browser), but only if it's not an existing file or folder.

I think rewrite %r{/(.*)}, '/$1.html' is what I need for the first half (ie, rewriting /foo to /foo.html), but I'm struggling with the conditional 'if file doesn't exist' part.

If it helps, under IIS, I had the following do the same:

<rule name开发者_开发技巧="RewriteHtml">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    </conditions>
    <action type="Rewrite" url="{R:1}.html" />
</rule>


If you have a look at the Rack::Rewrite Github page there is several ways to do the rewriting, just taking a guess here but you may be better off going for the Arbitrary Rewriting than the conditional.

require "rack/jekyll"
require "rack/rewrite"

use Rack::Rewrite do
    rewrite %r{/(.+)}, lambda {     |match, rack_env| 
        if File.exists?('_site/' + match[1] + '.html')
            return '/' + match[1] + '.html' 
        else
            return '/' + match[1]
        end
    }
end

run Rack::Jekyll.new

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消