Search code examples
erlangyaws

How to rewrite URL in Yaws/Erlang


How can I access yaws file without including it's extension? Say,

www.domain.com/listen.yaws => www.domain.com/listen

I could not find any specific documentation for this from yaws documentation/appmod.

I think the question is ultimately clarified!


Solution

  • You can find one example of how to accomplish this in the "Arg Rewrite" section (7.1.2) of the Yaws PDF documentation. Set the variable arg_rewrite_mod in your server configuration to the name of an Erlang module supporting rewriting:

    arg_rewrite_mod = my_rewriter
    

    To support rewriting, the my_rewriter module must define and export an arg_rewrite/1 function, taking an #arg{} record as its argument:

    -module(my_rewriter).
    -export([arg_rewrite/1]).
    
    -include_lib("yaws/include/yaws_api.hrl").
    
    rewrite_pages() ->
        ["/listen"].
    
    arg_rewrite(Arg) ->
        Req = Arg#arg.req,
        {abs_path, Path} = Req#http_request.path,
        case lists:member(Path, rewrite_pages()) of
            true ->
                Arg#arg{req = Req#http_request{path = {abs_path, Path++".yaws"}}};
            false ->
                Arg
        end.
    

    The code includes yaws_api.hrl to pick up the #arg{} record definition.

    The rewrite_pages/0 function returns a list of pages that must be rewritten to include ".yaws" suffixes; in this example, it's just the /listen page you mention in your question. If in arg_rewrite/1 we find the requested page in that list, we append ".yaws" to the page name and include it in a new #arg{} we return to Yaws, which then continues dispatching the request based on the new #arg{}.