简体   繁体   中英

HTACCESS REQUEST_URI without the filename

RewriteEngine On
RewriteCond %{REQUEST_URI} !(images)
RewriteRule ^(.*)\.(txt|rtf|docx?|odt|pdf|bmp|gif|jpe?g|png|tiff?)$ http://%{SERVER_NAME}/~abc123/uploader/process.php [nc]

Is there any way of not having to quote ~abc123/uploader but to modify my regular expression so that the request_uri without the filename is dynamically passed through?

I've tried looking at removing the filename from the request_uri and also changing my regular expression but to no avail.

What I'm trying to do is to make sure certain file types are processed by a PHP script and cannot be accessed directly.

Here are two clues that might help you:

First, you can use those keywords into your regular expression (I let you google for more information) : %{SCRIPT_FILENAME} and %{REQUEST_URI}

Second, here's an example of how to use it:

 # (1) if domain name is static:
 RewriteCond %{HTTP_HOST} ^(.*)\.s\.(.*) [NC,OR]
 RewriteCond %{HTTP_HOST} ^(.*)\.static\.(.*) [NC]
 # (2) and it's not the JavaScript directory:
 RewriteCond %{REQUEST_URI} !^/js/(.*)$
 # (3) *always* add /templates/ (if not there):
 RewriteRule /(templates/)*(.*) /templates/$2 [L]

And a few people know that you can even change the whole destination filename this way (note: the STATIC and PATH_LOCAL variable is an environment variable that I've calculated a few steps before):

# If static...
RewriteCond %{ENV:STATIC} 1
# ...first test to see if the file exists in the language path:
RewriteCond %{DOCUMENT_ROOT}/%{ENV:PATH_LOCAL}/%{ENV:EXT}%{REQUEST_FILENAME}  -f  
# It exists => rewrite filename then end:
RewriteRule  ^(.+) %{DOCUMENT_ROOT}/%{ENV:PATH_LOCAL}/%{ENV:EXT}%{REQUEST_FILENAME} [QSA,L]
RewriteEngine On
RewriteBase   /
RewriteCond   %{REQUEST_URI}        ^(?!images)(.*)/[-\w\.]*$
RewriteRule   ^(.*)\.(txt|rtf|docx?|odt|pdf|bmp|gif|jpe?g|png|tiff?)$   http://%{SERVER_NAME}/%1/process.php [NC,L]

will do what you ask. The (?!...) is a negative lookahead ie don't include images. The [-\\w.]*$ bit will match normal file names. What I don't understand is that a http://%{SERVER_NAME}/... redirect without the [R] is just a normal internal rewrite why you don't just do

RewriteRule  ^(?!images)(.*)/[-\w]*\.(?:txt|rtf|docx?|odt|pdf|bmp|gif|jpe?g|png|tiff?)$  $1/process.php [NC,L]

Without any conds or

RewriteCond  %{REQUEST_URI} !^images
RewriteCond  %{REQUEST_URI} (txt|rtf|docx?|odt|pdf|bmp|gif|jpe?g|png|tiff?)$
RewriteRule  ^(.*)/.*       $1/process.php [NC,L]

if you want to keep it easier to understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM