Note that there are some explanatory texts on larger screens.

plurals
  1. PODrupal 7 - URL rewriting with hook_url_*_alter() doesn't seem to be working
    text
    copied!<p>Here's my situation: I have a bunch of HTML pages in sites/default/files/pdf. I want to serve them as is so I have links to them in my Drupal site. However, one of the requirements is that all the URLs of these HTML pages must not contain any extensions. In addition, I want it to act in such a way that when users go to example.com/sites/default/files/pdf/somehtmlfile, the URL will show as example.com/pdf/somehtmlfile and also when users visit example.com/pdf/somehtmlfile, example.com/sites/default/files/pdf/somehtmlfile will be served instead.</p> <p>From my independent research, it seems that I should be using hook_url_inbound_alter() and hook_url_outbound_alter(). However, I seem to be doing something wrong because the URL does not change at all.</p> <p>Below is my code. I created a module called html_extension_remover (not very imaginative name, I know). I have successfully activated the module and some debugging statements are run successfully, so I know that the module is running.</p> <p> <pre><code>function html_extension_remover_url_outbound_alter(&amp;$path, &amp;$options, $original_path){ $pdf_regex = '|^sites/default/files/pdf(/.*)?|'; $pdf_new_path = 'pdf'; if (preg_match($pdf_regex,$path, $matches)) //rewrite all request to sites/default/files/pdf to pdf, looks nicer if (count($matches)==1) $path = $pdf_new_path; else $path = $pdf_new_path . $matches[1]; //append the rest of the URL, after the Regex match if (strpos($path, $pdf_new_path)!=FALSE) //URL contains pdf, means viewing converted PDFs in pdf dir if (strpos($path, '.htm')!=FALSE){ //if viewing .htm/.html file $path = substr(0, strpos); //strip extension from URL } $pdf_new_path = 'sites/default/files/pdf'; $pdf_regex = '|^pdf(/.*)?|'; if (preg_match($pdf_regex, $path, $matches)){ if (count($matches)==1){ $path = $pdf_new_path; } else{ $path = $pdf_new_path.$matches[1].'.htm'; } } } function html_extension_remover_url_inbound_alter(&amp;$path, &amp;$options, $original_path){ $pdf_new_path = 'sites/default/files/pdf'; $pdf_regex = '|^pdf(/.*)?|'; if (preg_match($pdf_regex, $path, $matches)){ if (count($matches)==1){ $path = $pdf_new_path; } else{ $path = $pdf_new_path.$matches[1].'.htm'; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload