Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
Try ThisRewriteRule ^(.*)\/$ $1.php [NC]for examplehttp://www.exapmle.com/contact-us/
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this questionHere is my current .htaccess codeRewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+)$ $1.php [NC,L]it is works only in removing .php extensionfromhttp://localhost/mysite/news.php?category=cat1&id=1tohttp://localhost/mysite/news/cat1/1/and fromhttp://localhost/mysite/news.php?category=cat1&year=2011&month=10&day=25&id=1tohttp://localhost/mysite/news/2011/10/25/1How to write complete .htaccess for the clean url above?
How to remove .php extension and add slash on the url? [closed]
It seems, that eithermod_rewriteis not installed, or enabled, or that you have set theAllowOverride-directive for the specific directory toNone. Change it to (at least)FileInfo
Options +FollowSymlinks RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f # not a file RewriteCond %{REQUEST_FILENAME} !-d # not a directory RewriteRule ^(.+)$ index.php?params=$1 [L]as you can see, i'm trying to convert anything likemysite.com/x/y/ztomysite.com/index.php?params=x/y/zhowever, it is not working. i tried mysite.com/home and put a breakpoint on the first line in index.php, but got a 404.any ideas as to why this isn't working for me? thanks for anything!
RewriteEngine not Rewriting URL locally?
Sure, you can do this easily without having to mess with cryptic RewriteEngine commands. (RewriteEngine has its place, but it's certainly not needed for something as simple as this.)Redirect permanent / http://newdomain.com/The Redirect directive automatically preserves anything following the portion of the path it's been instructed to redirect. Thedocumentation for the Redirect directiveexplains this with an example:Example:Redirect /service http://foo2.bar.com/serviceIf the client requestshttp://myserver/service/foo.txt, it will be told to accesshttp://foo2.bar.com/service/foo.txtinstead.
Quick htaccess questionI am changing the domain associated with a site and want to know if I can setup the htaccess to make the following types of redirects:Redirecthttp://www.oldomain.com/contact-ustohttp://www.newdomain.com/contact-usBasically a global redirect that redirects to the new domain but keeps the rest of the URL that the user typed.UPDATE:I ended up using the following code and it works perfectlyOptions +FollowSymLinks RewriteEngine On RewriteCond %{HTTP_HOST} ^olddomain.com$ [OR] RewriteCond %{HTTP_HOST} ^www.olddomain.com$ RewriteRule (.*)$ http://www.newdomain.com/$1 [R=301,L]
Changing Site Domain
RewriteRule ^http://([^/]*)/questions/(\d+)/(.*)$ http://$1/questions/question_handler.php?qid=$2Your(.*)was probably too greedy so it was usinghttp://mysite.com/questions/123/my-question-nameas the first group matched
I'm trying to write a .htaccess rule that would redirect someone asking forhttp://mysite.com/questions/123/my-question-nametohttp://mysite.com/questions/question_handler.php?qid=123Here's what i wrote so far (it's not working):Options +FollowSymLinks RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?(.*)$ [NC] RewriteRule ^(.*)/questions/(\d+)/(.*)$ http://%1/questions/question_handler.php?qid=%2$1 [R=301,L]Any help is much appreciated.
how to write a .htaccess redirect like stackoverflow does for its questions
You could test against the "Referer" header, you can't really rely on that but it's the best possible.E.g.http://jsfiddle.net/QmnKR/one of the headers will beReferer: http:// fiddle.jshell.net/QmnKR/show/light/
When creating websites, I like to let my clients view the work in progress. At the moment I do this by uploading their website to a directory, and use .htaccess to password protect that directory. But keeping track of passwords and ensuring the directory is still protected after an update is becoming an issue.I have now created a user login system for my clients where they can login and be redirected to a preview of their site (in an iframe on the page preview.php?c=clientName).I have looked into various ways of redirecting the client site to the preview page and the easiest has been using .htaccess, but this redirect still affects the site when in an iframe.Is there any way to stop the .htaccess redirect when the site is in an iframe?
.htaccess redirect unless in iframe
You could use PHP Internal Functions like memory-get-usagehttp://php.net/manual/de/function.memory-get-usage.phpor access a Shell Script that gives you some kind of Information about the current load of the Server. And then depending on that Information set a Redirect via Headers.However, Remember that if your server breaks down, most likely the PHP Script wouldn't be executed and no redirect would happen. So, depending on your Infrastructure you can handle this over a secondary Server (a Load-Balancer perhaps).If you can narrow down the most likely cause of a breakdown, try to fetch it there, for example if your MySQL Connection fails, fetch that, and direct the User to your "busy page".
is it possible to use php to redirect users to pagei.e. busy.phpwhen the server is busy or overcrowded, or something similiar? thanks :))
redirecting users if server is overcrowded or busy using php?
The following will handle the simple case you show. You'll need to add additional logic if you need to allow for other parameters in the query string or file names before the ?.RewriteEngine On RewriteCond %{QUERY_STRING} ^i=(.*) RewriteRule ^.* /#Video:%1? [NE,R=permanent]Why is this tricky?RewriteRule doesn't look at the query string, so you have to use RewriteCond to evaluate the QUERY_STRING variable and capture the part you'll need later (referenced via %1)the hash character (#) is normally escaped, you must specify the [NE] flagThe trailing ? on the substitution string is required to suppress the original query stringI tested this on Apache 2.2.
Problem:Visitors open the urlwebsite.com/?i=133r534|213213|12312312but this url isn't valid anymore and they need to be forwarded towebsite.com/#Videos:133r534|213213|12312312What I've tried:During the last hours I tried many mod_rewrite (.htaccess) rules with using Query_String, all failed. The last message inthis topicshows a solution for this problem, but what would be the rule in my situation.I'm very curious how you would solve this problem :)!
301 Htaccess RewriteRule Query_String
If your web server supportsmod_rewrite, you could do something like this:RewriteEngine On RewriteRule ^js/script\.js$ js/script.phpIf you have more than one script, you could generalize thatRewriteRuleby using a backreference from the test pattern:RewriteRule ^js/(.*)\.js$ js/$1.php
I have some javascript that is generated by PHP. Currently I am including the javeascript in the html using<script type="text/javascript" src="js/script.php">But I want to use<script type="text/javascript" src="js/script.js">Now script.js does not exist, but I want it to redirect to script.php without the user knowing.Can this be done with .htaccess?
Redirect script.js to script.php
Assuming you want to do a redirect:RewriteRule ^/blog/photos/photos/(.*)$ /blog/photos/$1 [R]
i have a url like thishttp://example.com/blog/photos/photos/gallery/image/1.And i need to remove the second photos folder. How do i remove the part usingmod_rewriteand.htaccess?For your interest /blog is my document root.Thanks a lot for any suggestions, SteveEDITYou should know that the URLs being generated by Wordpress 3.0 und NextgenGallery.http://example.com/blogis my document root. That means i have installed Wordpress into the folderblog.The first slug afterblogis the page i have my gallery associated with.The second slug is the name of the album and could be renamed to everything you want. It is just a placeholder for my galleries.galleryis the name of the gallery.
Remove part of URL
You should start by adding this to the .htaccess in your public folder:RewriteCond %{REQUEST_URI} ^/wordpress.* RewriteRule .* - [L]However, this is not the whole story. You also need to edit /etc/apache2/sites-available/ with this addition (to tell Rails not to process anything in /blog as part of the app):<Location /wordpress> PassengerEnabled offAlso in /etc/apache2/apache2.conf you may need to tell Apache to make any directory index (e.g. wordpress/) execute an index.php file if there is one:DirectoryIndex index.php
I want to run an instance of wordpress within my rails app. I currently have wordpress files housed in public/wordpress, but I need to configure my .htaccess file to allow both types of requests. How do I do that? currently, .htaccess is:General Apache optionsAddHandler fcgid-script .fcgi RewriteEngine On RewriteRule ^$ index.html [QSA] RewriteRule ^([^.]+)/!$ $1.html [QSA] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] ErrorDocument 500 "Application error Application failed to start properly"
How do I edit .htaccess to allow both rails and wordpress requests?
If you're redirecting to a different website you have to specify 'http://' at the front, otherwise Apache it will interpret it as a file on the server.RewriteEngine On RewriteCond %{HTTP_HOST} ^www.example.com [nc] RewriteRule (.*) http://example.com/$1 [R=301,L]
hello im having problem with my site when i typehttp://example.comit works fine but when i typehttp://www.example.comit displays page cannot be found ,what is the problem i couldnot find , i tried .htaccess redirection alsoRewriteEngine On RewriteCond %{HTTP_HOST} ^www.example.com [nc] RewriteRule (.*) example.com/$1 [R=301,L]it is not workingany help will be appreciated
site not working with url www
You have to install and enable the mod_speling module in apache and set the CheckCaseOnly Directive to On in your .htaccessCheckCaseOnly On
I need to make accessing directories on my server case insensitive.How do I do that using htaccess?
Make Folders in Apache Case Insensitive using .htaccess
You could add aconditionto exclude URLs that can be mapped to actually existing files:RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^.* controller.phpThe-fkeyword will test if the absolute path in%{REQUEST_FILENAME}is a path to an existing regular file in the filesystem and!-fis just the inverse.But if you have a fixed list of directories you want to exclude, you could also do this:RewriteCond $0 !^(assets|foo|bar)/ RewriteRule ^.* controller.phpThis condition tests if the match of the wholeRewriteRulepattern (referenced with$0) does not begin with neitherassets/norfoo/norbar/. If you don’t want to process the match you could also use a negated expression directly in yourRewriteRuledirective:RewriteRule !^(assets|foo|bar)/ controller.php
If i use:RewriteEngine On RewriteRule ^.* controller.phpIt would send all requests to controller.php But if controller.php included a css file (/assets/css/main.css) then it wouldn't work, as when the browser called it, it would just redirect to controller.phpIs there a way i can fix this?
HT Access - Mod Rewrite
Try these rules:RewriteRule ^index\.html$ / [L,R=301] RewriteRule (.+)\.html$ /$1 [L,R=301]
I would like to get rid of all the file extensions on my site. Except when they are on the index i would like it to say nothing...change this foo.com/index.htmlto this foo.com/and when the user goes to another page like foo.com/contact-us.htmlit will be foo.com/contact-usRewriteEngine On RewriteRule ^ this is where i get confused :(Thanks in advance!
Using ModRewrite to get rid of extentions
As far as I know, there is no conditional for DirectoryIndex. You could simulate that with a mod_rewrite directive like this one:RewriteCond %{REMOTE_ADDR} your_ip RewriteCond -d RewriteRule (.*)/$ $1/index.htmlIf you want to exclude other visitors of the site from viewing index.html then also useRewriteCond %{REMOTE_ADDR} !your_ip RewriteRule (.*)/index.html$ $1/index.php
Is it possible to make the DirectoryIndex value in a.htaccessfile conditional based on IP, so that - for example - my IP see'sDirectoryIndexas index.html and everyone else seesDirectoryIndexas index.php?Is there a solution other thanmod_rewrite?
conditional DirectoryIndex in .htaccess
Just found out how to fix that issue - just put this into your virtual host configuration in order to override global http.conf:<Files ~ "^\.ht"> Order allow,deny Allow from all Satisfy All </Files>SourceTHIS is the correct answer for sure (tested), but the op abandoned his question :/
I can't commit .htaccess files from my Windows SVN client (TortoiseSVN). The error that is returned is:Could not read status line: Existing connection was forcibly closed by the remote host.And here is basically what my vhost looks like in Apache:<VirtualHost *:80> DocumentRoot /var/www/mydomain.com/legacy/trunk/html ServerName mydomain.com <Directory /var/www/> FileETag MTime Size AllowOverride All </Directory> <Directory /var/www/tools> AllowOverride All </Directory> <Location /svn> DAV svn SVNPath /var/svn/repos/MyRepo # Limit write permission to list of valid users. # Require SSL connection for password protection. # SSLRequireSSL ErrorDocument 404 default AuthType Basic AuthName "Authorization Realm" AuthUserFile /etc/httpd/conf/.htpasswd Require valid-user </Location> </VirtualHost>How can this be changed, so that .htaccess files can be committed?
Why doesn't Subversion allow to commit .htaccess files?
Here's the solution:RewriteRule ^(4[^/]*)$ /feedback.php?sms_code=$1 [L] # # BEGIN wordpress RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END wordpressI left the default Wordpress rules in place, and added my own conditional rule above, making sure to terminate [L] processing if the condition was met
The following rewrite passes a string starting with the number 4 as a variable to process.php :RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(4[^/]*)$ /process.php?variable=$1 [L]So thishttp://www.domain.com/4shoppingis mapped tohttp://www.domain.com/process.php?variable=4shoppingBut I want to extend this last rewrite rule to basically state:if word begins with 4, map to /process.php?variable=$1 else map to /index.phpThe second (else) part of this statement is the basic WordPress rewrite rule. So for example:http://www.domain.com/shoppingwhich has no 4 will be directed tohttp://www.domain.com/index.php?shopping (I believe this is how WordPress permalinks work!)
mod_rewrite : if / else type RewriteRule
You need three .htaccess files :/.htaccess/app/.htaccess/app/webroot/.htaccessIf the one you pasted in your question is the one at the root of your website, that's probably where your problem comes from. These directives file would rewrite URLs to project.com/webroot/, which doesn't exist. It should redirect to project.com/app/webroot/, which will in turn rewrite to index.php?url=$1 (relative to project.com/app/webroot/).I'm not pasting the files here; the three of them are available in the CakePHP releases as well as in the Book:http://book.cakephp.org/2.0/en/installation/url-rewriting.html(check the 3rd item in the page).
Greetings!I have CakePHP based app on shared hosting I wonder if there's a way to clean up the url through .htaccess. What bugs me is that I have to have index.php in it or I get a 404:project.com/index.php/controller/methodInitially I was getting a 404 error no matter what and my host admin ended up setting RewriteEngine off and this is what it looks like now<IfModule mod_rewrite.c> RewriteEngine off RewriteRule ^$ webroot/ [L] RewriteRule (.*) webroot/$1 [L] </IfModule>Is there fix for this without the .htaccess? As it is right now, does it pose any type of security risk?Thanks
CakePHP and .htaccess in shared hosting environment
As the parameters in the URL query may have an arbitrary order, you need to use a either oneRewriteConddirectivefor every parameter to check or for every possible permutiation.Here’s an example with aRewriteConddirective for each parameter:RewriteCond %{QUERY_STRING} ^([^&]&)*opendocument(&|$) RewriteCond %{QUERY_STRING} ^([^&]&)*part=1(&|$) RewriteRule ^bunch\.of/unneeded/crap$ /page.php/welcome? [L,R=301] RewriteCond %{QUERY_STRING} ^([^&]&)*opendocument(&|$) RewriteCond %{QUERY_STRING} ^([^&]&)*part=2(&|$) RewriteRule ^bunch\.of/unneeded/crap$ /page.php/prices? [L,R=301]But as you can see, this may get a mess.So a better approach might be to use aRewriteMap. The easiest would be a plain text file withkeyandvaluepairs:1 welcome 2 pricesTo define your map, write the following directive in your server or virual host configuration (this directive is not allowed in per-directory context):RewriteMap examplemap txt:/path/to/file/map.txtThen you would just need one rule:RewriteCond %{QUERY_STRING} ^([^&]&)*opendocument(&|$) RewriteCond %{QUERY_STRING} ^([^&]&)*part=([0-9]+)(&|$) RewriteRule ^bunch\.of/unneeded/crap$ /page.php/%{examplemap:%2}? [L,R=301]
I have a few messy old URLs like...http://www.example.com/bunch.of/unneeded/crap?opendocument&part=1http://www.example.com/bunch.of/unneeded/crap?opendocument&part=2...that I want to redirect to the newer, cleaner form...http://www.example.com/page.php/welcomehttp://www.example.com/page.php/pricesI understand I can redirect one page to another with a simple redirect i.e.Redirect 301 /bunch.of/unneeded/craphttp://www.example.com/page.phpBut the source page doesn't change, only it's GET vars. I can't figure out how to base the redirect on the value of these GET variables. Can anybody help pls!? I'm fairly handy with the old regexes so I can have a pop at using mod-rewrite if I have to but I'm not clear on the syntax for rewriting GET vars and I'd prefer to avoid the performance hit and use the cleaner Redirect directive. Is there a way? and if not can anyone clue me in as to the right mod-rewrite syntax pls?Cheers,Roger.
301 Redirecting URLs based on GET variables in .htaccess
You can set access rules for ASP.NET or WCF web application in web.config file.HOW TO: Control Authorization Permissions in an ASP.NET Application
Is there a way to get URI based access control directly in IIS that works with static content, ASP, WCF services and anything else that comes in looking something like an HTTP request?Particularly I want the access control to be a bullet proof as possible preferably making the decisionbeforeIIS even tries to figure out what to service the request with.This linksort of hints that this can't be done but it's old and I'd be very surprised if what I'm looking for doesn't exist.This linkhas a few other options (and a less "aggressive" community)An ideal solution would be able to declare that everything (staticanddynamic content) under a given URL (for examplehttps://dns.name/some/path/*) needs a login and the user must be in some group. Also, I'd rather set it up with a username/passord file (at least for now) rather than AD or some windows account system.In short I want access control and I don't want to be writing code to get it.Thisseems related but I'm not sure it's quite the same.
.htaccess for IIS?
You can set theQSA flagto automatically append the originally requested query string to the new one:RewriteRule ^$ index.php?page=home [L,QSA] RewriteRule ^adm$ index.php?page=adm_home [L,QSA] RewriteRule ^adm/stats$ index.php?page=adm_stats [L,QSA]
I'm not too inexperienced with ReWrite (not a master either, though) so I was hoping somone might be able to help me.RewriteRule ^$ index.php?page=home [NC] RewriteRule ^adm$ index.php?page=adm_home [NC] RewriteRule ^adm/stats index.php?page=adm_stats [NC]Above is a snippet of my .htaccess file. As you can see, when someone visitshttp://www.example.com/adirectory/it actually calls on index.php?page=home, similarly if someone goes tohttp://www.example.com/adirectory/adm/it will still call index.php?page=adm_home within the "adirectory".What I'm wanting to achieve is this: I want to be able to display alerts on my pages, and to do this I want to simply be able to add alert=n (where n is a number) and thus have the redirect as index.php?page=home&alert=nHowever, I can't understand how this can be done, regex is confusing me. Seeking your help.
Query Strings & Mod ReWrite
I would expect you are on Apache 2.4<FilesMatch "\.(txt|pm)$"> deny from all </FilesMatch>Denyis an Apache 2.2 (and earlier) directive and is formerly deprecated on Apache 2.4 and moved (from abasemodule) to mod_access_compat (an optional extension). This module is probably not enabled, hence the error.You should be using the correspondingRequiredirective on Apache 2.4 instead. For example:Require all deniedReference:https://httpd.apache.org/docs/2.4/mod/mod_authz_core.html#require
i'm trying to set up this:https://github.com/oprel/emanonBut everytime i try to run post.cgi i receive this error on the error log:[Sat Jul 02 13:03:13.380647 2022] /fs5d/9kun/public/board/.htaccess: Invalid command 'Deny', perhaps misspelled or defined by a module not included in the server configurationThe 'Invalid command' is from .htaccess:<FilesMatch "\.(txt|pm)$"> deny from all </FilesMatch>Lines 3,4,5 What should i do?? I run apache with cgi.
.htaccess cgi perl - Invalid command 'Deny', perhaps misspelled or defined by a module not included in the server configuration
Have your htaccess rules file following manner. Please make sure to clear your browser cache before testing your URLs.RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Remove md5 from asset files RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d ##RewriteRule ^([^.]*)\.(?:[[:alnum:]]{32})\.([^.]*)\.(js|css)/?$ $1.$2.$3 [L] ##Since following has worked for OP, so adding it here, commenting above. RewriteRule ^(.+).([a-fA-F0-9]{32}).(.+)?(js|css)$ $1.$4 [L] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/$ $1 [L,R=301] # Send Requests To Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L]
Example:This => URL request ./any_folder/main.d25a1b054a0b0fbeb3def5a0ff50d01e.min.jsFor this => URL request ./any_folder/main.min.jsMy htaccess:RewriteEngine On # Remove md5 from asset files RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+).([a-fA-F0-9]{32}).(.+)?(js|css)$ $1.$3 [L] # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Send Requests To Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L]The above configuration does not work.
How to remove md5 from the filename in the requested URL for the file name without md5 using apache mod_rewrite?
As per your shown samples, please do have your root's htaccess Rule file as follows.RewriteEngine ON RewriteCond %{HTTPS} off RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]For yourpdirectory/folder have that htaccess Rule file as follows. You need to use same rules from root htaccess, you could inherit it.RewriteOptions InheritBefore RewriteEngine ON RewriteBase /p/ RewriteCond %{THE_REQUEST} \s/(citati[^.]*)\.php\s [NC] RewriteRule ^ %1? [R=301,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]*)/(.*)/?$ $1.php?autor=$2 [NC,L]
I am trying to make URL rewrite to nice looking URL with .htaccess. I was trying so many ways and always get or error 500 or nothing is happening. My folder tree looks like this:root index.php .htaccess p .htaccess citati.php ...What I am trying to do is from my "p" directory when someone goes tohttps://example.com/p/citati/Test-testto rewrite that tohttps://example.com/p/citati?autor=Test-testso I can have $_GET["autor"] in my citati.php file. I have many .php files in "p" directory so that is also what I need to worry about when rewriting. This is my .htaccess from rootRewriteEngine on RewriteCond %{HTTPS} off RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE] RewriteRule ^(.+)p/citati\/(.+)$ p/citati?autor=$1 [NC]And this is what I have now in my "p" directory .htaccess file:<IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L,QSA] RewriteRule ^p/citati\/(.+)$ p/citati?autor=$1 [NC] </IfModule>It doesn't matter if I can achieve this from root .htaccess file or from "p" directory .htaccess I just want somehow to do this.
Rewriting URL from other than root folder with .htaccess
Have it this way in your site root .htaccess:RewriteEngine on # remove www from url RewriteCond %{HTTP_HOST} ^www\.(example\.com)$ [NC] RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] # redirect /php/file.php to /file RewriteCond %{THE_REQUEST} \s/+(?:php/)?([^.]+)\.php [NC] RewriteRule ^ /%1 [NE,L,R=301] # internally map /file to /php/file.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/php/$1.php -f RewriteRule ^(.+?)/?$ php/$1.php [L]Make sure to test after clearing your browser cache.
I've been trying to achieve the following rewrite/redirect on a website I'm building but I'm struggling and can't find the right answer online.I want to rewritehttp://www.example.com/php/someFile.phpTo:example.com/someFileI have managed to achieve most of the desired result with the following code in my .htaccess root file but I need help with removing the php subdirectory:RewriteEngine on # remove www from url RewriteCond %{HTTP_HOST} ^www.example.com [NC] RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC] # redirect /file.php to /file RewriteCond %{THE_REQUEST} \s/([^.]+)\.php [NC] RewriteRule ^ /%1 [NE,L,R] # internally map /file to /file.php RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.*)/?$ /$1.php [L]Any help would be hugely appreciated.
Remove "/php/" subdirectory from URL with .htaccess
With your shown samples, could you please try following. Please make sure to place these rules at top of your .htaccess file. Also please do clear your browser cache before testing any URLs.RewriteEngine ON RewriteRule ^news/wp-content/uploads/2021/03/Swift-Vogue-580-1\.jpeg/?$ /news/make-mine-a-dealer-special-caravan-25644/ [R=301,NC,L]
I hope everyone is well.I am having a few issues trying to redirect an image that was linked in error from an email to a html page.For example the email points here -https://www.caravanguard.co.uk/news/wp-content/uploads/2021/03/Swift-Vogue-580-1.jpegBut should point here -https://www.caravanguard.co.uk/news/make-mine-a-dealer-special-caravan-25644/I have appplied the following to our .htaccess, but it does not appear to have worked. I have also done the same in the wordpress yoast plugin we use.redirect 301 /news/wp-content/uploads/2021/03/Swift-Vogue-580-1.jpeg /news/make-mine-a-dealer-special-caravan-25644/Any ideas?
Redirect one image to webpage Issue
you can use somethinglikethis. this stores the full URL in a cookie called LandingPageURL .RewriteEngine On RewriteBase / // if the cookie "LandingPageURL" is not set RewriteCond %{HTTP_COOKIE} !^.*LandingPageURL.*$ [NC] // then set it ... RewriteRule ^(.*)$ - [co=LandingPageURL:$1:.example.com:2678400:/]you probably want to use options likeHttpOnlyandSecurefor your cookiethere is also another method to set a cookie in .htaccess that goes like this :<If "%{HTTP_COOKIE} !^.*LandingPageURL.*$"> Header edit Set-Cookie ^(.*)$ $1;SameSite=None;Secure;HttpOnly </If>if you want to read the cookie with php you can go like this<?php if(!isset($_COOKIE['LandingPageURL'])) { error_log ("Cookie named 'LandingPageURL' is not set in ".__FILE__." #".__LINE__); } else { error_log("Cookie 'LandingPageURL' is set in ".__FILE__." #".__LINE__); error_log("Value of Cookie is: " . $_COOKIE['LandingPageURL'] ); } ?>
I'm usingWordPresson anApacheserver & would like to use my.htaccessto set a cookie when someone first lands on my site.If possible I'd setTWOCookies to:store the full URLstore the value in a parameter in the URL (e.g.teamname)Ordinarily in PHP, I'd just have:function set_user_cookie() { $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; if (!isset($_COOKIE['LandingPageURL'])) { setcookie('LandingPageURL', $url, time()+2678400, "/"); } } add_action( 'init', 'set_user_cookie');However we've been noticing issues with caching so I wonder if it's possible to achieve this within my.htaccessinstead.Example URL:www.example.com/?teamname=Chicago+Bulls
Set Cookie with htaccess
You can use^gallery/country/(?:.*[/.])?([a-zA-Z]{2})/?$See theregex demo. Details:^- start of inputgallery/country/- a literal string(?:.*[/.])?- an optional pattern matching.*- any zero or more chars other than line break chars as many as possible[/.]- a/or.([a-zA-Z]{2})- Group 1: two ASCII letters/?- an optional/$- end of string.
I want to pick up the ISO code (two letters) of a country using a REGEX expressionFor example, for the countryIrelandthe ISO code isie. The ISO code could be found after the slash/or after thelast.This is myRewriteRule:RewriteRule ^gallery/country(?:/[^/]*([a-zA-Z-9]{2}))?/?$ gallery/gallery.php?country=$1 [L,QSA]Here are some valid url's... If available, I want to pick the ISO Code:gallery/countrygallery/country/gallery/country/iegallery/country/ie/gallery/country/irelandgallery/country/ireland/gallery/country/ireland-love.iegallery/country/ireland-love.ie/gallery/country/ireland.69-love.ie/I've try to adapt the template formula that I use pretty much for all of my seo url's, but i'm having difficulties with this one. Here's what I've done so far.^gallery/country(?:/[^/]*([a-zA-Z-9]{2}))?/?$https://regex101.com/r/88azeh/6
REGEX expression: get the two letters after the slash or after the last dot
You need to pass value which you want to access through a query string to your index.php etc. In your .htaccess file try with following Rules once. Also make sure place your .htaccess file in root(same level along with youreventfolder is present, NOT inside event folder please). Later in your php code you could get/extract thevarvalue which is passed to it.Please make sure you clear your browser cache before testing your URLs.RewriteEngine ON RewriteRule %{QUERY_STRING} ^$ RewriteRule ^event/(.*)/?$ event/index.php?var=$1 [NC,L]
I have a url similar to:https://example.com/event/FI42382I have created a folder namedeventfrom which I want to use PHP to process theFI42382part.However, the last part is treated as its own directory. What do I need to do so that it is not a directory and instead I can manipulate the last path as a variable inevent/index.php?Sorry if I have worded the title poorly. I wasn't sure how to explain this.
How to get last part of URL to process in parent directory without creating a new child directory
+50I've made something like that for my vhosts on my local machine. Note that everything is defined in my vhost because you can't changeupload_tmp_dirandsys_temp_dirin runtime.<VirtualHost *:80> ServerName example.local ServerAlias www.example.local UseCanonicalName On <Directory /mnt/storage/Server/example> DirectoryIndex index.php #Options +Indexes +FollowSymLinks AllowOverride All Require all granted </Directory> php_admin_value upload_tmp_dir /mnt/storage/Server/example/temp/ php_admin_value sys_temp_dir /mnt/storage/Server/example/temp/ DocumentRoot "/mnt/storage/Server/example" ErrorLog ${APACHE_LOG_DIR}/example.error.log CustomLog ${APACHE_LOG_DIR}/example.access.log combined </VirtualHost>How to confirm that everything works:Create simple file:$dir = sys_get_temp_dir(); $file = tempnam($dir, rand()); var_dump(get_current_user()); var_dump($dir); var_dump('is_writable: ' . (int)is_writable($dir)); var_dump('is_readable: ' . (int)is_readable($dir)); var_dump($file);Upload script: create file named upload.php<?php if (isset($_POST['submit'])) { var_dump($_FILES); } ?> <!DOCTYPE html> <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="upload" id="upload"> <input type="submit" value="Upload Image" name="submit"> </form> </body> </html>
I am hosting multiple domains on my Apache Web Server on Ubuntu 18.04 but I cannot set the tmp upload directory for PHP.I tried putting this in my .htaccess for one of the domains, however nothing was stored when I tested.php_value upload_tmp_dir /var/www/example.com/tmp/My permissions for the /var/www/example.com/tmp/ folder are set at Chmod 775Is there a working way to set this in .htaccess or in the domain's .conf file?
PHP tmp upload directory for multlple domains
First you need to create an.htaccessfile in the root of the project.mymvc/.htaccessRewriteEngine On RewriteCond %{REQUEST_URI} !public/ RewriteRule (.*) public/$1 [L]Then, in the.htaccessfile in thepublicdirectory (which would bemymvc/public/.htaccess), you need to add aRewriteBasedirective to the existing code, so it looks like this:mymvc/public/.htaccess# Remove the question mark from the request but maintain the query string RewriteEngine On RewriteBase /mymvc RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.*)$ index.php?$1 [L,QSA]
I have a directory structuremymvc |--App |--Core |--logs |--public |--index.php |--vendor |--.htaccesswhat i want is that if someone hit my urlwww.example.com/mymvc/then all the request must go throughpublic->index.phpusing.htaccessfile. i do not have access to httpd.conf file.|--public |--index.phpI want mypublicfolder to be accessible only as a document root and request pass throughindex.phpfile insidepublicfolder. No one can access directlyApp,Core,logsetc. directories. Means i want my public folder to beDOCUMENT ROOT.
Apache Document Root using .htaccess
It's quite simple, actually.Just set theTarget URLto:https://new-site.com/page$1$1refers to the contents of the captured(\?.+)in the RegEx you provided.Seehttps://redirection.me/support/redirect-regular-expressions/for more details.See sample below:However, in that example, I used this RegEx:/page(|/|/?\?.+)$, which matches these URLs: (you can test it onRegExr, but you need to escape the/with a\; hence you'd use\/page(|\/|\/?\?.+)$, which is also accepted by theRedirectionplugin)http://example.com/page http://example.com/page/ http://example.com/page?q=test&s=test2 http://example.com/page/?q=test&s=test2
I'm using the WordPress Redirection plugin to redirect old landing pages to a new domain.I'm able to match URLs including any query strings and this redirects 100% to the new domain.Example:From:/page/(\?.+)?$To:https://new-site.com/pageHow can I include query strings in the target URL of the plugin so that the browsers will redirect to something like this:https://new-site.com/page?q=test&s=test2.htaccess# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /usbed/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /usbed/index.php [L] </IfModule> # END WordPress
WordPress Redirection plugin to include query parameters in target URL
to generate http 404 error from php can be done by this functionhttp_response_code(404);For referencePHP.net
This question already has answers here:How to create an error 404 page using PHP?(11 answers)Closed6 years ago.I want to show users a custom 404 error page but still want to return the error code 404 instead of 302.However, adding a custom 404 page and redirecting users to it changes the status code to 302. I still want the page to send a 404 status code. Is this possible by making any changes to the.htaccessfile or using PHP?
Return a 404 status code while redirecting users to a custom error page [duplicate]
+25first redirect to the same host-name on:443, then redirect towww.. ordinarywww.is just an alias in DNS, while most use the shorter non-www hostname for websites. you might have to extend the certificate, because it requires both host-names explicitly added, unless it's wild-carded.# rewrite to HTTPS RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]if you want to rewrite all towww.(or whatever the certificate says), just add another rule below. at first access, the non-SSL rule[L]is the last step, at the next access the SSL rule[L]is the last step, of the rewrite.# rewrite to www. RewriteCond %{HTTPS} on RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]also see this answerhere, concerningrobots.txtwith enforced SSL.when it is "still possible to use HTTP" ...maybe consider another location for the.htaccessfile - or create directories per host-name, which just redirect.
I have a PHP app on Heroku with an SSL certificate for the www version of the domain name. I need all requests (to both www and non-www) to go to via https, and I have added .htaccess to that affect. However, there are still circumstances where it's possible for a user to access the http version and I don't understand why.Here is my .htaccess:RewriteEngine on RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$ RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]My understanding is that this should force all users to access viahttps://www, but that doesn't always happen. For example, Google sometimes provides search results without thehttpsand the links open insecurehttpinstead.Any ideas about what I'm doing wrong?
Force Heroku PHP app to use https for both www and non-www versions
You can just typepermalink: prettyin your _config.yml.Source:https://jekyllrb.com/docs/permalinks/#builtinpermalinkstyles
I'm building a small Jekyll site with a number of pages. I would really like to get the page (notpost) links to a pretty state like:foo.com/bar/But I can't figure out how to get past:foo.com/_site/bar/index.htmlI can link to:foo.com/bar.htmlOf course, but that only returns my YAML front material. As you can tell, I haven't quite grokked the Jekyll naming system. Is there an easy way to do this within Jekyll, or will I have to rewrite the.htaccessfile?
pretty url for jekyll page
Relative links will use the protocol and host from the base URL. The base URL is usually the one which can be seen in the URL bar. But it is possible to change the base URL explicitly using thebase tag.This means if you have a base URL with http as protocol set in your page it will still use http instead of https even though you've accessed the site with https and the reference is relative, i.e. like this:<base href="http://example.com/">To fix it either remove the base tag or change it to use https instead of http:<base href="https://example.com">
I noticed when accessing a site using HTTPS I get errors in the JS console when trying to include CSS or JS files from a relative path such as this:<link rel="stylesheet" type="text/css" href="css/demo.css?id=14" />Mixed Content: The page at 'https://mysiste.com/' was loaded over HTTPS, but requested an insecure stylesheet 'http://mysiste.com/css/demo.css?id=14'. This request has been blocked; the content must be served over HTTPS.What's the ideal solution for this scenarios?Should I just force all the HTTP accesses to be redirected to HTTPS?Or is there a way to tell the server to serve all relative paths using HTTPS?
SSL for relative paths?
Try with:<IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule>
I have a simple AJAX request that callshttp://myexamplefeed.com/feed/23213I just moved this site to a new server, and all of a sudden I'm getting this error:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource athttp://myexamplefeed.com/feed/23213. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’).The thing is, in my .htaccess file I've tried to match *:<IfModule mod_headers.c> Header set Access-Control-Allow-Origin: * </IfModule>andhttp://myexamplefeed.com:<IfModule mod_headers.c> Header set Access-Control-Allow-Origin: "http://myexamplefeed.com" </IfModule>and I still get theCORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’error.Isn't null referring to theHeader set Access-Control-Allow-Originvalue, and shouldn't I be able to alter it in my .htaccess file?UPDATE: That was in Firefox. In Chrome I'm getting this message:The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed
CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’, but it is not null
you can use this :RewriteRule ^([^/.]+\.pdf)$ /site-content/import/uploads/$1 [R,L]or this :RedirectMatch ^/([^/.]+\.pdf)$ /site-content/import/uploads/$1Clear your browser caches before testing this redirect.EDIT:The examples above redirect .pdf files only, to redirect both .pdf and .doc ,you can use this rule :RewriteRule ^[^/.]+\.(pdf|doc)$ /site-content/import/uploads%{REQUEST_URI} [L,R]
I am trying to create a rewrite rule similar to the one belowRewriteRule ^/?(.*+/.pdf)$ /site-content/import/uploads/$1 [L,R=301]Any url request similar tohttp://hostname/filename.pdfShould redirect tohttp://hostname/site-content/import/uploads/filename.pdfBut it should not redirect if the request file name is inside a sub folder and also it should not redirect the urls other than .pdf or .doc fileshttp://hostname/sub-page/filename.pdf http://hostname/sub-page/sub/filename.pdf http://hostname/sub-page http://hostname/image.png
.htaccess redirect for .pdf/.doc file in the root folder
Well if you to want to allow/thumbs/directories, it depends how they are being blocked in the first place. If they're blocked with normal Apache access permissions, then something like this will do it, but must go in the main server config at root level or in a<VirtualHost>and not in a.htaccessfile.<DirectoryMatch "/thumbs/"> Require all granted </DirectoryMatch>Or for Apache before 2.4:<DirectoryMatch "/thumbs/"> Order allow,deny Allow from all </DirectoryMatch>Allowing is quite different from blocking with a forbidden response that you cited. You have to ask why is it not already allowed if it's within the web document root? Then open up that block.
I've can easely find a lot of .httaccess blocking examples, but in my case I would actually do the quit opposite, and allow access from all in subfolders matching(^|/)/thumbs/(/|$)If you have a directory named 'blah' that you want to block, but it can occur anywhere in your directory tree, use the following: RewriteEngine On RewriteRule (^|/)blah(/|$) - [F]Any body who know how to accomplish this?
Allow access to a directory
One of the notes onhttp://php.net/manual/en/features.http-auth.phpsuggested adding this:SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0That helped. It appears the default.htaccessconfig of thesymfony/standard-editionis not enough (at least in some Environments).
In a project using Symfony 2.8.14 I am using a very basic setup to enable basic HTTP Authentication in Symfony as described inhttp://symfony.com/doc/2.8/security.htmlsecurity.ymlsecurity: encoders: Symfony\Component\Security\Core\User\User: plaintext providers: in_memory: memory: users: myuser: { password: mypassword, roles: 'ROLE_USER' } firewalls: default: anonymous: ~ http_basic: ~ access_control: - { path: ^/myroute, roles: ROLE_USER }When accessing/myrouteon my local server I am prompted with the HTTP basic auth prompt. However, after entering the correct credentials, it just keeps showing me the prompt.On a remote server there will be infinite "redirects" to the same route with a401status code after entering the correct credentials.Both servers are running Apache 2.4 with PHP via FastCGI. There are other threads suggesting to add# Sets the HTTP_AUTHORIZATION header removed by apache RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]to the/web/.htaccessdue to a specific problem with Apache running PHP via FastCGI. However, this is already incorporated into thesymfony/standard-edition(and is also present in my.htaccess).I don't know what else to try.
Symfony basic HTTP authentication not working
Your second approach was almost correct (in fact, exactly that would work in.conffile).In per-directory context (Directoryor.htaccess), thePatternis matched against only a partial path: the directory path where the rule is defined is stripped from the path before comparison - up to and including a trailing slash!. The removed prefix always ends with a slash, meaning the matching occurs against a string whichneverhas a leading slash.Therefore:RewriteRule ^isso/(.*)$ http://127.0.0.1:63837/$1 [P]
I have isso app running onlocalhost:63837and I'd like to proxy requests fromhttps://www.domain.com/issoThese were my approaches:RewriteRule https://www.domain.com/isso/(.*)$ http://127.0.0.1:63837/$1 [P] RewriteRule /isso/(.*)$ http://127.0.0.1:63837/$1 [P] RewriteRule /isso(.*)$ http://127.0.0.1:63837/$1 [P]Normally I'd adjusthttpd-vhost.confbut in this case I can't do that on my hoster (uberspace).<Location "/isso"> ProxyPass "http://127.0.0.1:63837" ProxyPassReverse "http://127.0.0.1:63837" </Location>Also, I don't like to use a subdomain for this.
How to redirect subfolder as proxy in htaccess?
To forcehttps://wwwonly for the www.example.com , you can use :RewriteEngine on #redirect http non-www to https://www RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ RewriteRule (.*) https://www.example.com/$1 [R=301,L] #redirect https non-www to www RewriteCond %{HTTPS} on RewriteCond %{HTTP_HOST} ^example\.com$ RewriteRule (.*) https://www.example.com/$1 [R=301,L]
I am trying to force https and redirect non-www to www:domain.com ==>https://www.domain.comwww.domain.com ==>https://www.domain.comThe problem is I have many sudomains and I don't have wildcard ssl (for now) so I want :(x).domain.com (except www.domain.com) ===> http://*.domain.comIs that possible ?All the ansewers i found and tested only force https or redirect all non-www to www my problem is i don't want subdomains get https except for www and redirect non-www to www
htaccess force https and redirect non www to www if not have a subdomain
Try this one :Route::get('about{extension}', function() { return 'About page'; })->where('extension', '(?:.html)?');You can also use RouteServiceProvider to catch the extension if you have many pages that needs this pattern (thanks @Mike) ://app/Providers/RouteServiceProvider.php public function boot(Router $router) { $router->pattern('extension', '(?:.html)?'); parent::boot($router); }and then in your routes.phpRoute::get('about{extension}', function() { return 'About page'; });
What would be the easiest way to add .html and have it work both ways?example.com/about -> works!example.com/about.html -> works!I can add ".html" to the route, but then it doesn't work without.Route::get('about.html', function () { return 'About page'; });
Laravel appending .html to route (and also have it work without the .html)
Quick AnswerIf your server is using Apache, add the following snippet to your api's respective.htaccessfile:<IfModule mod_headers.c> Header set Access-Control-Allow-Headers "Authorization" </IfModule>More detailsin the above snippet, we are asking Apache to allowAuthorizationheader:Header set Access-Control-Allow-Headers "Authorization"you can add multipleheadersin one line, like this, but keep in mind that it's advised toonly allow the headers required by your app.Header set Access-Control-Allow-Headers "Authorization, X-Requested-With"Side NoteIn a related note, people often need to allow cross-origin request (also known as Cross-Origin Resource Sharing or CORS). The following snippet allows cross requests fromhttps://example.comorigin:Header set Access-Control-Allow-Origin "https://example.com"or you might use"*"to allow requests from all origins:Not RecommendedHeader set Access-Control-Allow-Origin "*"Wrap up<IfModule mod_headers.c> # To allow headers Header set Access-Control-Allow-Headers "Authorization" # to allow cross origin request from https://example.com Header set Access-Control-Allow-Origin "https://example.com" </IfModule>
I have an Laravel based API on my Server. And I try to access this api from an AngularJS Frontend. Unfortunately this error shows up.Where do I have to add the configuration to allow the Authorization Header? I tried to find a solution but couldn't manage to solve it.I tried to insert it in thehttpd.confand in the.htaccessof the Angular frontend but unfortunately it didn't work:Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Request header field Authorization is not allowed
You can use this code in/app/.htaccess:RewriteEngine on RewriteBase /app/ # external redirect from actual URL to pretty one RewriteCond %{THE_REQUEST} /index\.php\?param=([^\s&]+) [NC] RewriteRule ^ %1? [R=302,L,NE] # internal forward from pretty URL to actual one RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+?)/?$ index.php?param=$1 [L,QSA]
When user enters url likehttp://example.com/app/abcd123/I want to show hime page fromhttp://example.com/app/index.php?param=abcd123Without changing URL in browser.I put .htaccess file inside app folder with codeRewriteEngine on RewriteCond %{REQUEST_URI} ^/index.php [NC] RewriteCond %{QUERY_STRING} ^param=(.*) RewriteRule (.*) http://example.com/app/%1? [R=301,L]
htaccess rewrite rule with single parameter
+50FYI: You can check apache version withapachectl -V # or /<pathwhereapachelives>/apachectl -VFor the fastCGI setup, see if this link helps.http://redconservatory.com/blog/getting-django-up-and-running-with-hostgator-part-2-enable-fastcgi/Basically, if you want to run the script in/, you can use mod_rewrite to serve static files directly (as/mediain the example below), and every other path being served by the WSGI script:AddHandler fcgid-script .fcgi Options +FollowSymLinks RewriteEngine On RewriteRule (media/.*)$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]Note that, as you are using Flask, you will have to override theSCRIPT_NAMErequest variable (as describedhere), otherwise the result ofurl_for()will be a string starting in/index.fcgi/...:#!/usr/bin/python #: optional path to your local python site-packages folder import sys sys.path.insert(0, '<your_local_path>/lib/python2.6/site-packages') from flup.server.fcgi import WSGIServer from yourapplication import app class ScriptNameStripper(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): environ['SCRIPT_NAME'] = '' return self.app(environ, start_response) app = ScriptNameStripper(app) if __name__ == '__main__': WSGIServer(app).run()
I have created a simple application in Python/Flask, which has a home url (www.site.com/). I have acquired a HostGatorshared accountto host it, so I only have access to.htaccess, but no other Apache config files.I setup a FastCGI script to run the application (followingthese instructions), but they require the URL to have a/index.fcgior any other path.Can I make the root path (/) be served directly by the FastCGI script?Also, folders like/static/and/favicon.icoshould be served by Apache instead.What I have now as.htaccessis:AddHandler fcgid-script .fcgi DirectoryIndex index.fcgi RewriteEngine On RewriteBase / RewriteRule ^index.fcgi$ - [R=302,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.fcgi/$1 [R=302,L]I'm not sure, but I think the Apache version is 2.2.
How can I run a FastCGI script in root url (/ - without path)?
You can use this rule in your site root .htaccess:Options -MultiViews RewriteEngine On RewriteRule ^cars/([\w-]+)/(\d+)/?$ car.php?car=$2&name=$1 [L,QSA,NC]
I'm trying to write a .htaccess file that would enable me to writesampleurl.com/car.php?car=1&name=Audi-A4And than it would make the url:sampleurl.com/cars/Audi-A4/1my current code is:RewriteEngine on RewriteRule ^cars/([0-9][0-9])$ /cars/$1/ [R] RewriteRule ^cars/([0-9][0-9])$ /cars/$1/ [R] RewriteRule ^cars/([0-9][0-9])/$ /car.php?car=$1Are there any ideas how could I make this work?EDIT:Both codes work:RewriteEngine On RewriteRule ^([^/]*)/([^/]*)$ /car.php?name=$1&car=$2 [L]andOptions -MultiViews RewriteEngine On RewriteRule ^cars/([\w-]+)/(\d+)/?$ car.php?car=$2&name=$1 [L,QSA,NC]but when I open the website, it shows just the page, without linked css file, how can I link the css file to that webpage?Current CSS Link code:<link rel="stylesheet" type="text/css" href="style/main.css">
How to rewrite url that uses get variables with .htaccess
Open Chrome Developer Tools, go to the network tab, click on preserve log, and load your site over http.If you see a 301 or 302 redirect to https then something on the server is telling your browser to go to https.If you see a 307 redirect to gyros then the site has, or had, a Strict-Transport-Security (aka HSTS) header set on it to force https and Chrome has cached that policy. This is a security feature web servers can use to enforce https. Check the HTTP Headers returned to see if that's the case and, if no such header is being sent than you can view and clear an old policy by using this page into your address bar: chrome://net-internals/#hsts
I recently enabled ssl in apache2 and everything was going well, but now everytime I try to accesshttp://example.com/I get redirected tohttps://example.com/I checked my default.conf, apache2.conf for some directions but didn't find any.<VirtualHost *:80> ServerAdmin webmaster@localhost ServerName example.de DocumentRoot /var/www <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny allow from all </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined</VirtualHost> <VirtualHost *:443> DocumentRoot /var/www ServerName example.com SSLEngine on SSLCertificateFile /root/server.crt SSLCertificateKeyFile /root/server.key </VirtualHost>I also double checked the .htaccess files in all directorys. Is there a way to look up from where or what is redirecting? Are any other ways to redirect ALL http requests to https?
Disable ssl/https redirection apache2
You can create a rewrite rule in .htaccess that routes the movie urls to movie.php as follows:movie/123:RewriteRule ^movie/(\d+)$ movie.php?id=$1 [L]movie/id/123:RewriteRule ^movie/id/(\d+)$ movie.php?id=$1 [L]movie/title-of-movie:RewriteRule ^movie/(\S+)$ movie.php?slug=$1 [L]movie/title/title-of-movie:RewriteRule ^movie/title/(\S+)$ movie.php?slug=$1 [L]combination movie/123/title-of-movie:RewriteRule ^movie/(\d+)/(\S+)$ movie.php?id=$1&slug=$2 [L]Edit: added a full .htaccess example for 1 required with up to 2 extra optional parameters with a fallback on index.php if the url is not for movies.Options -Indexes IndexIgnore */* Options FollowSymLinks AddDefaultCharset utf-8 <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^movie/([^/]+)/?([^/]*)/?([^/]*)$ movie.php?param1=$1&param2=$2&param3=$3 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule . index.php [L] </IfModule>^to match from the beginning$to match until the end?for 0 or 1 occurrence+for 1 or more occurrences*for 0 or more occurrencesIf the url rule does not match and the file does not exist then it will route the url to index.php, but you can remove that last part if you don't want that.
So I've been searching for a while now and can't find anything specific on how to create a pretty url / seo / slug url type system WITHOUT sending everything to a index.php or moving things into subfolders.Basically I'm making a website which you can currently go to urls like movie.php?id=#### / show.php?id=####. Ideally I'd like the url to be movie/#### or movie/id/#### (or down the line slugs of the name that i can use to grab the right one) etc.Is there a way to do it without having a single index.php router or am I just going to have to rewrite all my files to adhere to this style?
.htaccess / php url rewriting without routing?
If you want to access the file as an HTTP resource instead of direct disk access (like in your question), you can do the following:Code in .htaccess (placed the "nonpublic_test" folder):RewriteEngine on RewriteCond %{REQUEST_URI} ^.*/restricted/.*$ [NC] RewriteCond %{QUERY_STRING} !^.*key=SECRET.*$ [NC] RewriteRule ^(.*)$ /$1 [R=403,L]Then in your showfile.php:<?php echo file_get_contents('http://www.domain.name.here/restricted/'.$_GET['file'].'?key=SECRET'); ?>This will prevent any access to the restricted folder and its contents but still allow your showfile.php script to access the file inside that folder and output it.
I'm trying to build a simple website which is going to let users upload files, and privately share them with other designated users. The problem is: I don't want anyone to be able to type in the url for a file to be able to get to it (then anyone could see it).I decided to try using.htaccessto prevent direct url access, however, I cannot figure out how to access the file myself. All of the uploaded files are going to go into asubfoldercalled"restricted".My".htaccess"file is:RewriteEngine on RewriteCond {%QUERY_STRING} !^.*key=SECRET.*$ [NC] RewriteRule ^restricted/(.*)$ showfile.php?file=$1My "showfile.php" file:<?php echo file_get_contents('[...]/restricted/'.$_GET['file'].'?key=SECRET'); ?>However, when I open"restricted/test.txt"or some other file in the restricted folder, it successfully redirects to"showfile.php?file=test.txt", however, I get a php error:Warning: file_get_contents([...]/restricted/test.txt?key=SECRET) [function.file-get-contents]: failed to open stream: No such file or directory in [...]/showfile.php on line 10It seems like even though the query string contains"key=SECRET", it is still trying to redirect.What I want: I want it to redirect on direct URL access, but that I can access it through the php page it's redirected to.
URL Rewriting to Privately Access Files
It's probably doesn't work because the rule doesn;t apply. In most cases the root is not empty, but contains a request to index.html or default.html . Give this snippet a try:RewriteEngine on RewriteRule "default.html" "http://mysubdomain.mydomain.com/" [P]
I'm trying to redirect only the root domain (and not its subfolders) to another URL, without changing the address. I'm using .htaccess and redirecting with [P] flag, which works fine for subdirectories but not for the root.When writing the following .htaccess everything works fine, but in 'regular' redirect and not proxy:RewriteEngine on Rewriterule ^$ http://mysubdomain.mydomain.com/ [R,L]When changing to mod_proxy, it doesn't work (does not redirect without an error):RewriteEngine on Rewriterule ^$ http://mysubdomain.mydomain.com/ [P]It is important to me to keep the original address in the browser address bar. any idea?Thanks
htaccess proxy redirect for root and only root
You should be able to do this<Files ~ "\.(tpl|yml|ini)$"> # Deny all requests from Apache 2.4+. <IfModule mod_authz_core.c> Require all denied </IfModule> # Deny all requests from Apache 2.0-2.2. <IfModule !mod_authz_core.c> Deny from all </IfModule> </Files> <FilesMatch "swagger\.yml$"> <IfModule mod_authz_core.c> Require all granted </IfModule> <IfModule !mod_authz_core.c> Allow from all </IfModule> </FilesMatch>Also you should remove the directives for the version you are not using. If you are using 2.4 then you don't need 2.2 directives there. However I left it since that's how you have it.
I have the following block in my.htaccessto deny download of configuration files# Disables download of configuration <Files ~ "\.(tpl|yml|ini)$"> # Deny all requests from Apache 2.4+. <IfModule mod_authz_core.c> Require all denied </IfModule> # Deny all requests from Apache 2.0-2.2. <IfModule !mod_authz_core.c> Deny from all </IfModule> </Files>But how can I allow all files which are namedswagger.yml?
Deny all configuration files except one in Apache
You can get rewrite base dynamically captured using a separate rule:RewriteEngine On RewriteCond $0#%{REQUEST_URI} ^([^#]*)#(.*)\1$ RewriteRule ^.*$ - [E=BASE:%2] RewriteCond %{THE_REQUEST} \?page=(\d+) [NC] RewriteRule ^ %{ENV:BASE}/%1/? [R=301,L]Explanation:You can use$0captured fromRewriteRulein yourRewriteCondbecausemod_rewriteactuallyprocesses a ruleset backwards. It starts with the pattern in theRewriteRule, and if it matches, goes on to check the one or moreRewriteCond.So as you can see in aRewriteCond, the LHS (test string) can use backreference variables e.g.$1,$2OR%1,%2etc but RHS side i.e. condition stringcannot usethese$1,$2OR%1,%2variables.Inside the RHS condition part only backreference we can use areinternal back-referencesi.e. the groups we have captured in this condition itself. They are denoted by\1,\2etc.In yourRewriteCondfirst captured group is([^#]*). It will be represented by internal back-reference `\1.As you can mark out that this rule is basically findingRewriteBasedynamically by comparing%{REQUEST_URI}and$0. An example of%{REQUEST_URI}will be/directory/foobar.phpand example of$0for same example URI will befoobar.php.^([^#]*)#(.*)\1$is putting the difference in 2nd captured group%2or\2. Here it will populate%2or\2with the value/directory/which is used later in setting up env variable%{ENV:BASE}i.e.E=BASE:%2.
I have the following RewriteRule which makes it so that someone going todomain.com/somepage/?page=3will be 301 redirected todomain.com/somepage/3/:RewriteCond %{THE_REQUEST} \?page=([0-9]+) [NC] RewriteRule ^ /somepage/%1/? [R=301,L]This is in a.htaccessfile in thesomepagedirectory.Now, thisworksfine... but it's a bit of a hassle. I have about a dozen pages that are paginated, all in their own directory. I would like to just be able to copy the.htaccessfile into each directory and not have to worry about editing each one. For example, I also wantdomain.com/someotherpage/?page=3to redirect todomain.com/someotherpage/3/, but to do this I'd have to edit the respective.htaccessfile and change thesomepagepart tosomeotherpage.It also causes problems when I copy my entire site to a different server. Normally, the site is placed in the root directory. However, when I'm running it locally, I place the entire site in a folder calleddev. So now I have to go through all of the RewriteRules and change it from/somepage/%1/to/dev/somepage/%1. This, as you can probably imagine, is incredibly tedious.So, is there a way of changing this so that the path that it redirects to is relative to the.htaccessfile, rather than from the server's root, so that I can reuse the same.htaccessmultiple times without changing it, and so that I can also move my entire site into adevdirectory without needing to change anything?Thanks.
Making RewriteRule portable/relative to the directory of the .htaccess file
You can do using .htacess redirect as @Arjar Aung provided.I used this way at my config fileif(strpos($_SERVER['HTTP_HOST'],'www')===false) { $config['base_url'] = 'http://example.com'; } else { $config['base_url'] = 'http://www.example.com'; }
I have a site where I have added the base_url() for calling the css and js files. The base_url() is withoutwww. It is working fine withhttp://example.combut not working withhttp://www.example.com. That is it is showing some issues like not taking the fonts, sessions etc. I have searched many solutions but not able to find the right one. Please tell me a solution.
site with www and without www is not acting same for baseurl in codeigniter
Comment out bothFilesMatchblocks:And use this code:RewriteEngine On RewriteCond %{REQUEST_URI} !^/index\.php$ [NC] RewriteRule ^\.|\.(ini|php)$ - [F,NC]
I have a folder structure like this:subdir |_ subsubdir |_ index.php |_ other_stuff.php |_ images |_ pic.jpg .htaccess config.ini index.phpContent of the .htacces file:Options +FollowSymLinks -MultiViews -Indexes Order Deny,Allow <FilesMatch "(\.ini$)|(\.php$)|(^\.)"> Deny from all </FilesMatch> <Files index.php> Allow from all </Files>My goal is to keep users from viewing subdir/subsubdir/index.php (and all other *.php files, no matter where, but this works already) butallowthem to see the index.php in the root directory.Currently, the user is obviously still able to see subdir/subsubdir/index.php, because all files named "index.php" are allowed, but I have no idea how to allowjustthe one in the root directory and deny all others. I have tried different things but endet up either completely denying or allowing them all.I feel like this should be a very easy task but I just can't figure it out.Things I have tried:<FilesMatch "\.\/index\.php"> Allow from all </FilesMatch> --- <FilesMatch "^index\.php$"> Allow from all </FilesMatch> --- <Files ./index.php> Allow from all </Files> --- <Files /index.php> Allow from all </Files>
Block index.php everywhere except in the root directory with .htaccess
Not fully random like PHP code but you can achieve something similar usingmod_rewriteusingTIME_SECvariable that represents seconds value of the current time. Consider this code:RewriteEngine On RewriteBase / # dont rewrite more than once RewriteCond %{ENV:REDIRECT_STATUS} .+ RewriteRule ^ - [L] # redirect all requests for php file to index file if %{TIME_SEC} is 0, 10, 20, 30, 40, 50 # or if %{TIME_SEC} is 1, 11, 21, 31, 41, 51 RewriteCond %{TIME_SEC} [01]$ RewriteRule ^.+?\.php$ index.php [L,NC] # redirect all requests for php file to index file if %{TIME_SEC} is 2, 12, 22, 32, 42, 52 # or if %{TIME_SEC} is 3, 13, 23, 33, 43, 53 RewriteCond %{TIME_SEC} [23]$ RewriteRule ^.+?\.php$ index2.php [L,NC] # redirect all requests for php file to index file if %{TIME_SEC} is 4, 14, 24, 34, 44, 54 # or if %{TIME_SEC} is 5, 15, 25, 35, 45, 55 RewriteCond %{TIME_SEC} [45]$ RewriteRule ^.+?\.php$ index3.php [L,NC] # redirect all requests for php file to index file if %{TIME_SEC} is 6, 16, 26, 36, 46, 56 # or if %{TIME_SEC} is 7, 17, 27, 37, 47, 57 RewriteCond %{TIME_SEC} [67]$ RewriteRule ^.+?\.php$ index4.php [L,NC] # redirect all requests for php file to index file if %{TIME_SEC} is ending in 8, 9 RewriteCond %{TIME_SEC} [89]$ RewriteRule ^.+?\.php$ index5.php [L,NC]
I am having one website and it is redirecting to five different index file randomly using php.www.xyzdomain.com/index.phpwww.xyzdomain.com/index2.phpwww.xyzdomain.com/index3.phpwww.xyzdomain.com/index4.phpwww.xyzdomain.com/index5.phpI want to redirect it using.htaccess, the same way it redirecting php.I found that using htaccess we can redirect urls like,Redirect 301 / http://www.xyzdomain.com/index.phporRedirect 302 / http://www.xyzdomain.com/index.phpCurrently i am doing that with usingphprandom array.<?php $urls = array("index.php", "index2.php", "index3.php", "index4.php", "index5.php"); $url = $urls[array_rand($urls)]; header("Location: http://www.xyzdomain.com/$url"); ?>Question: How to redirect multiple index randomly using .htaccess rules?
Multiple url redirect using .htaccess
Try addingOptions -MultiViewsbeforeRewriteEnginedirectiveOptions -MultiViews RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ /$1.php [L,QSA]Note:MultiViewsis about Apache content negociation (which is the problem here sincefilenamewill automatically be translated asfilename.phpexisting file). That's why you have to disable it.EDIT: right now, you can access same content by 2 different urls (with or withoutphpextension). To avoid duplicate content (which is bad for search engines) you can redirect extensions to extensionless equivalent with this codeOptions -MultiViews RewriteEngine On RewriteCond %{THE_REQUEST} \s/(.+?)\.php [NC] RewriteRule . /%1 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ /$1.php [L,QSA]
This question already has answers here:Remove .php from urls with htaccess(5 answers)Closed9 years ago.Well, I know that it should be done by .htaccess my .htaccess is in the root of my site and here it's contentRewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.phpAlso mod rewrite is enabled at my server. I have a form with an action on./getReadings.phpin it. But when I change it to./getReadingsit says that tehre isn't such file on server. What's my mistake?
Removing .php from url [duplicate]
Assuming that your images are in a common subfolder, for example/imagesinhttp://example.com/images/img.png, you can alter your rule to exclude this subdirectory completely, then add an errordocument. This .htaccess should be in your www-root.RewriteEngine On #If the file does not exist, and the url doesn't start with /images RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l RewriteCond %{REQUEST_URI} !^/images RewriteRule ^(.+)$ index.php?page=$1 [QSA,L] #If the rule above didn't match, and the file does not exist, use the ErrorDocument ErrorDocument 404 /404.phpSeeDocumentation for ErrorDocumentDocumentation for mod_rewriteFree friendship coupon for Apache(might or might not be expired)
I've been working with my own MVC system for a while now and it works great!I use this in my .htaccessRewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.+)$ index.php?page=$1 [QSA,L]Now, when a page (controller) doesn't exist, I redirect to /error(in the index.php file). But there are some scenarios when a picture will be deleted in a folder, and still be printed in the html page. This will automatically make the browsers call the picture, which doesn't exist (So it will call the /error page)Now what I want to do is that, when a picture, or any file, (except, php,html files i guess) I would like to redirect to a 404 file instead of the /error.I am certain that this could be solved in the .htaccess file, but me and Apache aren't so buddies at the moment. Anyone who is friend with Apache?Thanks!
.Htaccess redirect to 404 page when certain files doesn't exist
You can use this .htaccess:RewriteEngine On RewriteBase /site/public/admin/ RewriteCond %{THE_REQUEST} \s([^.]+?)(?:\.php)?\?caseid=([^&\s]+) [NC] RewriteRule ^ %1/caseid/%2/? [R=302,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)/caseid/([^/]+)/?$ $1.php?caseid=$2 [L,NC,QSA] ## hide .php extension snippet # To externally redirect /dir/foo.php to /dir/foo RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1/ [R=302,L] # add a trailing slash RewriteCond %{REQUEST_FILENAME} !-f RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301] # To internally forward /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.+?)/?$ $1.php [L]
First let me show you my .htaccess file code belowRewriteEngine On RewriteBase /site/public/admin/ ## hide .php extension snippet # To externally redirect /dir/foo.php to /dir/foo RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1/ [R,L] # add a trailing slash RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !/$ RewriteRule . %{REQUEST_URI}/ [L,R=301] # To internally forward /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.*?)/?$ $1.php [L]The code above works fine but what I would like to add to this is when I type the following URLhttp://localhost/site/public/admin/AccidentDetails/?caseid=12it should change to the followinghttp://localhost/site/public/admin/AccidentDetails/caseid/12/Not good at mode rewriting I would like have your opinion on that, please help.
formatting URL parameters using mod_rewrite
You must specify an option calledQSA or 'Query String Append':RewriteRule ^([a-z0-9-]+)\.html$ /index.php?cat=$1 [L,QSA]It will ensure that the original query strings are also included as part of your new URL.
My code isOptions -Multiviews RewriteEngine On RewriteBase / RewriteRule ^([a-z0-9-]+)\.html$ /index.php?cat=$1 [L]If I accessmysite.com/name-of-category.htmlit works, but if I accessmysite.com/name-of-category.html?anything=somethingit shows the webpage but$_GET["anything"]shows nothing.
HTACCESS friendly url and allow GET method
I had a similar problem when nginx that was listening on both http and https ports was forwarding the traffic to a local apache instance.In the nginx configuration i added:proxy_set_header X-Request-Protocol $scheme; #http or httpsIn the .htaccess file i added this:RewriteEngine On RewriteCond %{HTTP:X-Request-Protocol} ^http$ RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]
There are a thousand threads on this but I must be missing something as I can't get it to work.My nginx load balancer decrypts SSL traffic and proxies it (via Varnish) through to the content servers. It adds a custom header to the proxied request:proxy_set_header "IS-HTTPS" "1";I can SEE this HTTP header from the content servers:<?php var_dump($_SERVER["HTTP_IS_HTTPS"]); ?>This will outputstring(1) "1"on a HTTPS connection, andNULLon a HTTP.So, my .htaccess rules:RewriteCond %{HTTP:IS_HTTPS} !="1" RewriteRule ^(securebit.*)$ https:// %{HTTP_HOST}/$1 [R=301,L]Doesn't work. Just gets into a redirect loop.(NB: the space in "// %" isn't there. StackOverflow validation is falling over on it.)Neither do:RewriteCond %{HTTP:IS_HTTPS} !=1RewriteCond %{HTTP:IS_HTTPS} !1RewriteCond %{HTTP:HTTP_IS_HTTPS} !="1"RewriteCond %{HTTP:HTTP_IS_HTTPS} !=1RewriteCond %{HTTP:HTTP_IS_HTTPS} !1What simple, obvious and frustrating mistake am I making?
htaccess rewriteCond using custom http header
Put in the directory to deny access an .htaccess file containingdeny from allIf you have a sub-directory containing public files insert another .htaccess withallow from all
Directory structure for my website is like this:www/PSite/inc/public/The inc(include) directory is for where i will include all the important and secure PHP files where normally users have no access but only php code from the public directory can access into the inc directory.And in public direcotry i will have all public files and pages.I have heared that it's a better security system, and i want to do it using.htaccessfile.Assume i have a.htaccessfile in thePSitedirectory how i can redirect request atPSiteto/public/index.htmlso, users will be unable to reach atincdirectory? i was trying with this code, but it dosen't works with other files and folders inpublicdirectory.RewriteEngine On RewriteRule ^$ /public/index.php [L]Note that i have changed the path: localhost/PSite with psite.dev using httpd.conf and windows host fileHTTPD Conf:<VirtualHost 127.0.0.1> ServerName psite.dev DocumentRoot "C:\wamp\www\PSite" </VirtualHost>Thanks
using htaccess for public and private directory
Solution 1. Using CodeIgniter routingtry this in yourapplication/config/routes.php$route ['api/(:any)'] = "api/$1"; $route ['(:any)'] = "home/index/$1"; $route ['default_controller'] = "home";For any matching()in patter, you'l need to add respective$1or$2,$3.. based on position of that()patter. i.e for first()its $1, for second()its$2and so on.You'l need to set your default controller tohome.Solution 2. Using .htaccess page redirectionRewriteEngine On RewriteCond %{REQUEST_URI} !^/api(.*)$ RewriteCond %{REQUEST_URI} !^/home/index$ RewriteRule ^.*$ /home/index [R=301,QSA,L]
I am trying to redirect URL's with Codeighiter routing. I could not write routing for the following.If the URL comes with/api/some/someI want to redirect it toapi/some/some, otherwise I want to redirect the URL to/home/index.i.e if any URL starts withapi/i don't want to change that URL other wise i want to redirect it to default controllerhome/indexWhat i tried is mapping the codeigniter URL routing.$route['api/(:any)'] = 'api/(:any)'; $route['(:any)'] = 'home/index/';I am trying with codeigniter URL routing technique but i am not able to achieve this.Is this is the way to redirect URL's at codeigniter level with out touching server side redirection or is there any better approach to do this?
Codeigniter URL redirection and routing
It is becauseRewriteCondis only applicable to the very nextRewriteRule. Your last 2 rules execute for all the hosts includingbuddiesandbazaarand causes redirection loop.You need these rules:RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC] RewriteRule ^/?market/(.*)$ http://market.example.com/$1 [L,R=301] RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC] RewriteRule ^/?buddies/(.*)$ http://buddies.example.com/$1 [L,R=301] RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC] RewriteRule ^/?bazaar/(.*)$ http://bazaar.example.com/$1 [L,R=301]
I have .htaccess file like:RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC] RewriteRule ^/?market/(.*)$ http://market.example.com/$1 [L,R=301] RewriteRule ^/?buddies/(.*)$ http://buddies.example.com/$1 [L,R=301] RewriteRule ^/?bazaar/(.*)$ http://bazaar.example.com/$1 [L,R=301]It works fine in market subdirectory. It redirects to the subdomain. But, There is a problem with other 2 subdirectories.ERROR FOR OTHER 2 sub-domains:The page isn't redirecting properlyWhat should I do to overcome this problem?
redirect subdirectory to subdomain issue
You need to follow these steps to clone your WordPress website from production to staging server -1. First export database of production server WordPress website and open SQL file in an text editor. 2. Then find your domain name(domain.com) and replace it at all places with your domain name/test like domain.com/test. 3. Import production SQL file to test database from phpmyadmin. 4. Open staging WordPress admin like domain.com/test/wp-admin and go to Settings > Permalink section. Just click on the Save button to update htaccess file. 5. Optionally you can go to setting at admin page and save all general settings, menus and check Widgets area too. 6. Now you can access your domain.com/test WordPress website.
I am trying to make a clone of a Wordpress site into a subdirectory. So, I will have two installations, one in the root of the domain, and one in /test. My problem is that, even though I have changed the values for siteurl and home uri in database, my links will redirect to root. So, a page like domain.com/test/contact will redirect to domain.com/contact, which is not what I want.
Wordpress clone in subdirectory
Try adding these rules to your htaccess file:RewriteCond %{THE_REQUEST} \ /+([^\?\ ]+)\.php RewriteRule ^ /%1 [L,R=301]If you need to do the same with with.htmlextensions, then change thephppart of that condition to(php|html?).
I'm a beginner using htaccess and I don't know how to do what I want. I'd like to understand what I'm doing so I'd really appreciate if you can help me give me some advices for ver (very!) beginners... :) I'd like to:Redirect xxx.php, xxx.html or any extension to xxx (without extension)Now, my htaccess isRewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.phpand it works but just if I write xxx. But if I write xxx.php (I see the page :(, I'd like to redirect to xxx) and if I write xxx.html it doesn't show nothing.Finally. I've like to rewrite variables to friendly links i.e. If I have xxx.php?id=1 > I would like to redirect to xxx/usernameThank you in advance Best wishes and merry christmas! :)
htaccess rewrite without extension
As David points out, one way to work around this is to use mod_rewrite, but if you have Apache 2.4 or newer, you can use theIf directive, which is a lot cleaner:<Files foo-bar.php> <If "%{QUERY_STRING} =~ /foo=bar/"> ... </If> </Files>Note that the argument of the directive is actually a regular expression. It's incredibly powerful.
I can match files just fine when using this<Files foo-bar.php> ... </Files>however how do you match it if the string you're matching is like this?<Files foo-bar.php?foo=bar> ... </Files>
How to match query string in <Files> in htaccess?
Your regex is wrong. You cannot have$following another$in an input since$denotes end of text.This rule should work:RewriteEngine On # new rule to handle example.com/blah123/sys RewriteRule ^(\w+)/(\w+)/?$ /index.php?id=$1&mode=$2 [L,QSA] # your existing rule to handle example.com/blah123 RewriteRule ^(\w+)/?$ /index.php?id=$1 [L,QSA]
Mod rewrite novice here. I want to pass two URL parameters in the URL, but in a more friendlier format. If user passes, "example.com/blah123/sys", I should be able to extract the MySQL record "blah123" and the mode type "sys", in this case. Here's the example:URL:example.com/blah123/sysIn the .htaccess, I have:RewriteEngine On RewriteRule ^([^/.]+)/?$ index.php?id=$1The above works if the URL passed is: "example.com/blah123", but not "example.com/blah123/sys".I tried the following, but it is not working:RewriteEngine On RewriteRule ^([^/.]+)/?$/?$ index.php?id=$1?mode=$1I need to extract the "mode" type passed in the second argument. So, if the user enters "example.com/blah123/sys", I should be able to get the value "sys" from the URL. How can I do that? I want to use PHP, MySql, .htacess.UPDATE: My current .htaccess:# Use PHP 5.3 AddType application/x-httpd-php53 .php RewriteEngine On #RewriteRule ^([^/.]+)/?$ index.php?id=$1 RewriteRule ^([^/.]+)/([^/.]+)/?$ index.php?id=$1&mode=$2 [L,QSA]
How to create a friendly URL with two or more arguments using mod rewrite / htaccess?
Here's what happened:Googlebot saw, on some other page, a link to track.php. Let's call that page "source.html".Googlebot tried to visit your track.php file.Your robots.txt told Googlebot not to read the file.So Google knows that source.html links to track.php, but it doesn't know what track.php contains. You didn't tell Google not to index track.php; you told Googlebot not to read and index the datainsidetrack.php.AsGoogle's documentation says:While Google won't crawl or index the content of pages blocked by robots.txt, we may still index the URLs if we find them on other pages on the web. As a result, the URL of the page and, potentially, other publicly available information such as anchor text in links to the site, or the title from the Open Directory Project (www.dmoz.org), can appear in Google search results.There's not a lot you can do about this. For your own pages, you can use thex-robots-tagornoindex meta tagas described in that documentation. That will prevent Googlebot from indexing the URL if it finds a link in your pages. But if some page that you don't control links to that track.php file, then Google is quite likely to index it.
i'm using robots.txt to exclude some pages from spiders.User-agent: * Disallow: /track.phpWhen i search something refeered to this page, google says: "A description for this result is not available because of this site's robots.txt – learn more."It means that the robots.txt is working.. but why the link to the page is still found by the spider? I'd like to have no link to the 'track.php' page... how i should setup the robots.txt? (or something like .htaccess and so on..?)
Why google finds a page excluded by robots.txt?
Create an htaccess file in yourSHOW-STRdirectory with this:Order Allow,Deny Allow from all
I'm trying to "exclude" a directory (and all it's folder) from the rules in .htaccess file...Not sure if that's possible?The .htaccess file is like this:Order Allow,Deny Deny from all <Files ~ "\.(css|jpe?g|png|ico|gif|js)$"> Allow from all </Files> <Files "show.php"> allow from 127.0.0.1 </files>Now, I want to exclude an entire sub-directory... from these rules... i.e. Allow from all (for all file extensions in directory "SHOW-STR")The only way now, is to do it file by file ... but I wonder if there's a way to exclude a sub-directory?
Rule to allow folder in .htaccess file
Enablemod_rewriteand.htaccessthroughhttpd.confand then put this code in yourDOCUMENT_ROOT/.htaccessfile:RewriteEngine On RewriteCond %{REQUEST_URI} !^/[^/]{3}/ RewriteRule ^(.{3})(.+?\.(?:jpe?g|gif|bmp|png|tiff|css|js))$ /$1/$2 [L,R=302,NC]
I'm not sure if it's even possible to do this, because searching for answer didn't help (although to be honest, I'm not really sure how to even google this). Anyways, I have a domain for static files (images) media.mydomain.com . All images have random names and are just there in the home folder of the domain. Like this: media.mydomain.com/123abcdefgh.jpg . However, I would like to organize them into folders, so I wouldn't have 100.000 files in one folder. Basically, I would love to have something like this media.mydomain.com/123/abcdefgh.jpg . First 3 characters of the string is folder name, others are file name. This URL also looks fine and if there's no solution, I will go with it. However, maybe it's possible to use .htaccess and somehow make it take first 3 characters of the request uri and rewrite them into folder and the rest of the string into filename? So when you go to media.mydomain.com/123abcdefgh.jpg server will access media.mydomain.com/123/abcdefgh.jpg . I hope my question is clear. Is is possible to do this somehow? Thank you in advance for your help.
.htaccess first 3 characters as folder
Here is my full answer to avoid repeated characters in urls using lazy match as suggested by samurai8 in previous comments:FOR REPEATED SLASHS AND DASHESRewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{REQUEST_URI} ^(.*?)(/{2,})(.*)$ RewriteRule . %1/%3 [R=301,L] RewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{REQUEST_URI} ^(.*?)(-{2,})(.*)$ RewriteRule . %1-%3 [R=301,L] RewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{REQUEST_URI} ^(.*?)(_{2,})(.*)$ RewriteRule . %1_%3 [R=301,L]FOR REPEATED LETTERS IN WORDSRewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{REQUEST_URI} ^(.*?)a{3,}(.*)$ RewriteRule . %1aa%2 [R=301,L] RewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{REQUEST_URI} ^(.*?)b{3,}(.*)$ RewriteRule . %1bb%2 [R=301,L] RewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{REQUEST_URI} ^(.*?)c{3,}(.*)$ RewriteRule . %1cc%2 [R=301,L] . . .
I have the following url:example.com/helllllllllloAnd I was looking for a way to avoid repeated characters up to double.Inspired by this question/answersRemove Characters from URL with htaccessI have created the following htaccess document to avoid repeated characters. If the character is repeated more than 23 times the url is not completely rewrited and I was wondering if there is any possible improvment?RewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{REQUEST_URI} ^(.*)l{3,}(.*)$ RewriteRule . %1ll%2 [R=301,L]
.htaccess - how to remove repeated characters from url?
The AllowOverride Directive is set in the apache global configuration file. This file is managed by cPanel and it's important not to edit sections labeled not to edis as those edits will be lost.The configuration file is located at: /usr/local/apache/conf/httpd.confYou're looking for a section that looks like the following since the AllowOverride directive is only available inside a <directory> section of the configuration file.<Directory "/"> Options All AllowOverride All </Directory>After you ensure that this AllowOverride is enabled in the apache configuration you will need to let cPAnel know that you have updated the file by running the following command:/usr/local/cpanel/bin/apache_conf_distiller --updateMore about the AllowOverride Directive:http://httpd.apache.org/docs/2.2/mod/core.html#allowoverridecPanel Logs and Configuration Posters:http://go.cpanel.net/logposterhttp://go.cpanel.net/configposter
I'm using a cpanel/whm setup.htaccess files work fine for the base directory (public_html) but anything below that (public_html/stuff/) isn't processed. I'm aware I need to set AllowOverride, but where exactly do I enable this?
apache htaccess in subdirectories with cpanel/whm
Works using the redirectMatch ruleRedirectMatch 301 /category/(.*) /free/$1
I'm trying to 301 Redirect one category to another category in wordpress, for some reason wordpress isn't doing it automatically so this is what i have at the moment.RewriteRule ^category/?(.*)$ /free/$1 [R=301,L]I've tried this with no hope luck, any ideas why? been looking for a solution for 4h now and i just cant figure it out.Looks like my 7 hours battle is over (kinda sad it took me that long) here is what workedSolution:RedirectMatch 301 /category/(.*) /free/$1
Redirecting one category to another using .htacess - wordpress
I tried everything and nobody could help me. After much research, I found this and it works for me. So here my own answer, that may help others searching for the same thing.This will make that the URL showing the subdomain ("en.domain.com") doesn't change in the address bar and even if someone enters "domain.com/en/" it will rewrite the URL to "en.domain.com":RewriteEngine On RewriteCond %{HTTP_HOST} ^domain\.com$ RewriteRule ^en(/(.*))? http://en.domain.com/$2 [QSA,L,R=301]This will break the paths of your site, causing that styles and images won't show. Therefore you need to put this in your HTML code on every page of your site, according to the location of each page in the structure of your site:For the page in folder "en":<head> <base href="http://domain.com/en/" /> </head>For the page in folder "aaa":<head> <base href="http://domain.com/en/aaa/" /> </head>For the page in folder "bbb":<head> <base href="http://domain.com/en/aaa/bbb/" /> </head>You are welcome! :-)
I set up a subdomain on my web host like this:en.domain.com pointing to the folder /en/But when entering "en.domain.com" in the address bar, the URL changes todomain.com/en/And if I navigate further, let's say to folder "aaa", the URL turns intodomain.com/en/aaa/Is there a way to make the subdomain stay in the address bar, like this?:en.domain.com/aaa/
Subdomain redirect with htaccess without changing URL in the address bar
No idea how that rule is working for you. First, it loops. Second, there is no capture groups for$2and$3, but it doesn't matter because$1is always "search" anyways. I'm assuming you've pasted a partial snippet of a rule that you have that works.The reason why&,%, or/isn't being matched is because your regex says:[-0-9a-zA-Z]+which means:one or more letters, numbers, or a dash. So no&,%, or/. So you can add those into the square brackets:RewriteRule ^([-0-9a-zA-Z/%&]+) search.php?id=$1&ff=$2&ffid=$3However, keep in mind that the URI isdecodedbefore any rules get applied. This means if the URI looks like:/foo%28barYou don't need to match against%, because the URI gets decoded into:/foo(barand you need to match against(. A better option may to just match against everyexceptdots:RewriteRule ^([^.]+) search.php?id=$1&ff=$2&ffid=$3or whatever youdon'twant in your match.Try:RewriteRule ^([^.]+)$ search.php?id=$1 [B]The difference here is the$to bound the match to the end of the URI, and theBflag ensures the&gets encoded.
In my .htaccess file I have defined following rule,RewriteRule ^([-0-9a-zA-Z]+) search.php?id=$1The above rule works fine if I am browsinghttp://example.com/abcdI need to use the symbols& % - /in the url like:http://example.com/ab&cdWhat changes have to be made to the rule for this to work?
How to handle special characters like & and / in .htaccess rules?
I'm not sure if Laravel's internal environment handling works with folders, but it definitely works with subdomains. You could choose to setup your app using two Apache vhosts, one namedtest.example.local, one namedreal.example.localand then set the environment option in Laravel like this:$env = $app->detectEnvironment(array( 'test' => array('test.example.local'), 'real' => array('real.example.local'), ));There's a second option using .htaccess: You could set this in your .htaccess...SetEnv LARAVEL_ENVIRONMENT test SetEnv LARAVEL_ENVIRONMENT realThen you could set your environment in Laravel like so:$env = $app->detectEnvironment(function() { return $_SERVER['LARAVEL_ENVIRONMENT']; });
I have a site that is in the testing phase, so it connects not to the real data but to a local copy of a database.My customer needs now a fast link to retrieve some urgent and important pdf reports, so I need to set up another version of the site that links to the "real data".I can create two environments ("local" and "real") with different database connections, and I would like to give the opportunity to select the environment via the URL (I know it's not pretty from a security point of view, but let's take this for granted).So I would like to use:my.ip.address/mysiteto use the test dbmy.ip.address/mysite/realto use the real db, redirecting to the URLs without the "real folders".F.ex.:/mysite/real/adminshould redirect to/mysite/adminbut selecting the "real" environment on Laravel 4.is it possible to pattern-match also folders in Laravel 4 or is it possible only for domains? In other words, does this work?$env = $app->detectEnvironment(array( 'test' => array('*/mysite/*'), 'real' => array('*/mysite/real/*'), ));If so, I just can't figure out how to write the .htaccess rule, I've triedRewriteRule ^/real(.*)$ $1But it won't work.
How to select environment in Laravel 4 using .htaccess?
Try this code :RewriteCond %{HTTP_HOST} ^www.newdomain.com$ RewriteRule ^(.*)$ http://www.mydomain.com/sub-page [R=301,L]
I have a wordpress site which is www.mydomain.com . This site has a page www.mydomain.com/sub-pageI also have a new domain, www.newdomain.com which is pointed to the same root/site, but I want people that use this domain to get redirected to www.mydomain.com/sub-pageHere is my htaccess, Im not sure of the syntax, but at the moment this is doing nothing, www.newdomain.com simply loads www.mydomain.comRewriteCond %{HTTP_HOST} ^www\.newdomain\.com$ [NC] RewriteCond %{HTTP_HOST} ^newdomain\.com$ [NC] RewriteRule ^(.*)$ http://www.mydomain.com/sub-page [R=301,L]
how to redirect new domain to sub page of old domain in htaccess
You can't do it with a RewriteRule alone because Apache will ignore the query string. Here I'm doing the redirect if the query string contains the ID we're looking for.RewriteCond %{QUERY_STRING} Itemid=134 [NC] RewriteRule ^.*$ http://%{HTTP_HOST}/madplan/lav-madplan? [R=301,L]Remember when you're testing that your browser will cache your 301 redirect, so you'll need to clear your cache to see any changes.
I got this Joomla problem - google seems to have indexed a menu entry of mine which i had removed, but i forgot to remove the entry in the menu so now google have indexed this site:http://www.madplanuge.dk/?Itemid=134I wan to redirect it (.htaccess) to this url:http://www.madplanuge.dk/madplan/lav-madplanHow would you do that. i have already tried following:RewriteRule ^\?Itemid=134http://www.madplanuge.dk/madplan/lav-madplan?[R=301,L]RewriteCond %{REQUEST_URI} ^\?Itemid=134$RewriteRule ^\?Itemid=134$http://www.madplanuge.dk/madplan/lav-madplan?[R=301,L]Neither of the above solutions worked.
.htaccess rewrite request url starting with question mark
The infinite loop asking for your password is what you want to see. That means you typed in your password wrong. The Internal Server 500 Error means you have another issue in your code. The reason your username and password aren't working is because your server expects the password to be hashed.Change your .htpasswd file to:Guest:$apr1$u5E5vgOR$6rPNEYkeaF5IVE4c3FyKM0(The password is GuestPassword)
I am attempting to set up htaccess to restrict access to a particular folder. I currently have as follows:Htaccess:AuthType Basic AuthName "Restricted area" AuthUserFile /home3/user/public_html/.htpasswd require valid-user ErrorDocument 404 "Error" ErrorDocument 401 "Error" ErrorDocument 403 "Error"htpasswd:Guest:GuestPasswordUsing this method I will either have a 500 server error returned, OR it will loop and continuously prompt me for authentication.Any help is appreciated!ALSO: I usedshowphp()to get the Document root. So AuthUserFile path should be correct.Thanks!
htaccess Internal server error, authentication loop
Wouldn't it be easier to just set up a Virtual Host?DocumentRoot "actual/path/to/application" ServerName appnamethis would mean that when you typehttp://yourdomain.com/appname it will resolve to http://root/actual/path/to/applicationMaybe I am not understanding the problem properly - but i would use a VirtualHost instead of complex Mod_Rewrite rules.
I'm using ZF2 (Zend Framework 2, v2.2) and I would like thathttp://www.foo.com/path/to/app/redirect to the public folder.I've tried a lot of solution but not of them allow the url to point to /path/to/app/public/index.php, while only displaying /path/to/app/.I would appreciate any solution as I cannot create a virtual host as described in app skeleton README file.Any help very much appreciated.Cheers, Greg.
Redirect to public folder when using ZF2
FromErrorDocumentAlthough most error messages can be overridden, there are certain circumstances where the internal messages are used regardless of the setting of ErrorDocument. In particular, if a malformed request is detected, normal request processing will be immediately halted and the internal error message returned. This is necessary to guard against security problems caused by bad requests.It seems, that a "414 Request-URI Too Large" is considered severe enough, to ignore an appropriateErrorDocument 414setting.
Using htaccess, I've managed to make error pages show up beautifully on my site like such:ErrorDocument errorcode /pathtopageThe included code works for every single error code I've tested except forError 414 Request URI too long. It seems that Apache is completely ignoring the htaccess file in this case - is there a way to get it to work?
How to get apache to load custom page for 414 error
Add these rules in the htaccess file in your document root (formaindomain.com):RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?maindomain.com$ [NC] RewriteRule ^(subdomain1|subdomain2|subdomain3) - [L,F]This will return a "403 Forbidden" if you try to access/subdomain1,/subdomain2, or/subdomain3from the maindomain.com host. If you don't want to return a 403, you can also redirect:RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?maindomain.com$ [NC] RewriteRule ^(subdomain1|subdomain2|subdomain3) / [L,R=301]This redirects any access to the subdomains from the maindomain.com host to the document root.Rules to add to the top of htaccess files found in thesubdomain folders:RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?maindomain.com$ [NC] RewriteRule ^ - [L,F]orRewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?maindomain.com$ [NC] RewriteRule ^ / [L,R=301]
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed10 years ago.Improve this questionHow can I block users from viewing sites that are located in the folder of main domain? For example: main domain is www.maindomain.com. When I create subdomain for another account in cPanel, it creates folder it it is accesible if someone type for example www.maindomain.com/subdomain. I would like to block certain folders, but leave others, as I have pages in folder: wwwmaindomain/contact-us. How can I do that? Hope it's clear enough :)
Block access to url with .htaccess [closed]
Maybe one solution is to exclude all image and CSS files from the rule, like this:Options +FollowSymlinks -MultiViews RewriteEngine On # Add or remove file types in the next line if necessary. RewriteCond %{REQUEST_URI} !\.(css|jpg|png|gif|bmp|js) [NC] RewriteCond %{REQUEST_URI} !underconstruction\.html [NC] RewriteRule .* /underconstruction/underconstruction.html [R=302,L]Other options are to replace relative with absolute paths in the links to those files or to use the BASE element as described in thisanswer
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed10 years ago.Improve this questionI have been trying to redirect all requests under a domain to an underconstruction folder with the following:RewriteEngine On RewriteCond %{REQUEST_URI} !=/underconstruction/ RewriteRule ^ /underconstruction/ [R=301]But it doesn't seem to work.I tried this (and it works):RewriteEngine On RewriteCond %{REQUEST_URI} !=/underconstruction/underconstruction.html RewriteRule ^ /underconstruction/underconstruction.html [R=301]But I don't see the images and CSS that it comes with it.Does anyone have any idea?
Redirect all requests under a domain to an under construction folder [closed]
You must be specific if you want to redirect onlydomain.comtowww.domain.comand retain sub-domains (such astouch.domain.com) :RewriteEngine On RewriteCond %{HTTP_HOST} ^domain\.com [NC] RewriteRule ^(.*) http://www.domain.com/$1 [L,R=301]
I redirected non-www request to www through .htaccess Rewrite Rule.RewriteCond %{HTTP_HOST} !^wwwRewriteRule (.*) www.%{HTTP_HOST}/$1 [L,R=301]But now I am having problems with subdomains. When I am accessingtouch.111.comthen the above rule redirects totouch.www.111.com(which is not accessible), and the website breaks on touch devices.Please advise me on how to fix the above problem.
Problem with subdomains using .htaccess to redirect non-www URLs to www (301)
If your version of Apache supports it, you may be able to use "negative lookahead" and write the first RewriteRule like this:RewriteRule ^(.*)\.(?!js|css)([^.]*)$ $1\.phpThe[^.]part makes sure the(.*)\.matches everything until the last., "positioning" the negative lookahead at the right spot.
I have a.htaccessfile that redirect any extension to a non-extension url and displays therequestedfilename + .php. It works great with the(.*)part of the conditions.When I typedomain.com/file.htmlordomain.com/file.xmlit displays thefile.phpand the url looks likedomain.com/file.I just would like to know how to exculde extensions like .js and .css from the expression. I don't want to redirect them to any other php file.I tried things like:(.*!.(js|css))instead of(.*)but I can't find a working solution...The current code is this:<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / # # to display the name.php file for any requested extension (.*) # RewriteRule ^(.*)\.(.*) $1\.php # # to hide all type of extensions (.*) of urls # RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.(.*)\sHTTP/.+ RewriteRule ^(.+)\.php $1 [R=301,L] # # no extension url to php # RewriteCond %{REQUEST_FILENAME}.php -f RewriteCond %{REQUEST_URI} !/$ RewriteRule (.*) $1\.php [L] </IfModule>
.htaccess redirect all extension except css and javascript
Couple of problemsRewrite flags go in square-brackets, eg[QSA,L]YourRewriteConditionsyntax looks incorrect. TryRewriteCond %{REQUEST_FILENAME} !-fJust to be on the safe side, anchor your expression to the start of the stringRewriteRule ^(.*)$ index.php?url=$1 [QSA,L]Lastly,RewriteEngineand subsequent modifiers requires theFileInfooverride. Make sure your server config or virtual host<Directory>section for your document root hasAllowOverride FileInfoUpdateHere's a typical rewrite scheme from an MVC project. This will ignore real files, directories and symlinksRewriteEngine On RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
I'm trying to get my.htaccessfile to forward all URLs to a single page with url parameters so that I can handle the page retrievals that way. What I want to happen is this: say the user types inhttp://mysite.com/users/danit should forward to the pagehttp://mysite.com/index.php?url=/users/dan.Similarly, if the user accessed the URLhttp://mysite.com/random-linkit should forward tohttp://mysite.com/index.php?url=random-linkHere is the code I tried in my.htaccessfile, but it just keeps throwing a 500 error at me:<IfModule mod_rewrite.c> RewriteEngine On RewriteCond % (REQUEST_FILENAME) !-f RewriteRule (.*)$ index.php?url=$1 <QSA,L> </IfModule>I UPDATED MY CODE TO THIS AND IT STILL THROWS A 500 ERRORI changed the < and > to [ and ] and I removed the space after the % in the RewriteCond, but it still throws an error.<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*)$ index.php?url=$1 [QSA,L] </IfModule>I'm a novice when it comes to.htaccess, so any help would be greatly appreciated, because I don't know what's causing the server to timeout.
Can't get mod_rewrite IfModule to work in .htaccess
RewriteEngine on RewriteBase / #if not already blog.website.com RewriteCond %{HTTP_HOST} !^blog\.website\.com$ [NC] #if request is for blog/, go to blog.website.com RewriteRule ^blog/$ http://blog.website.com [L,NC,R=301]
I have few websites on my host. Most of them have their own domain.I want to prevent access to my subdomain folder via maindomain.com/subdomain .I want to make it able to open only via subdomain.maindomain.comDisable access if possible, or just redirect it to subdomain.
Prevent access to folder of subdomain on main domain
Redirect to replace all spaces to hyphensSolves the problemRewriteEngine On RewriteCond %{THE_REQUEST} (\s|%20) RewriteRule ^([^\s%20]+)(?:\s|%20)+([^\s%20]+)((?:\s|%20)+.*)$ $1-$2$3 [N,DPI] RewriteRule ^([^\s%20]+)(?:\s|%20)+(.*)$ /$1-$2 [L,R=301,DPI]
This question already has answers here:Closed11 years ago.Possible Duplicate:301 Redirect With SpacesRight now I'm redirecting every Image hit to the html page which contains the image.RewriteEngine on RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain.com/.*$ [NC,OR] RewriteCond %{HTTP_REFERER} (bing.com|google|yahoo|stumbleupon.com|reddit.com|pinterest.com) [NC] RewriteRule (.*)\.(gif|jpg|png)$ /$1.html [R,L]Since the Images often include spaces but the html pages always use hyphens, I need a solution to also replace all spaces, %20 and + symbols with hyphens
Replace space, %20 and + with hyphens [duplicate]
.htaccees# RewriteCond is condition - make rewrite only if file doesn't exists # (.+) means "any character, one or more" RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+)$ processor.php?mySecretCode=$1PHP<?php echo $_GET['mySecretCode']; ?>
My regex tries to match all results and redirect to a page. I want to send the address requested to the page:RewriteRule ^/[\w\W]*$ processor.php [R,NC,L]For instance, my address is:www.mywebsite.com/mySecretCode123I want my php file to be able to read it:<?php echo $mySecretCode123; /* outputs 'mySecretCode123' */ ?>How can I do this?
.htaccess match anything and send to PHP file
RewriteCond %{HTTP_HOST} ^(www\.)?washington\. [NC] RewriteRule ^(.*)$ http://www.mysite.com/washington [R=301,L]In yourRewriteRuleyou have/$1which matches the(.*)wildcard set of parentheses. This is why you're getting the path from the old URLs appended.I combined your 2RewriteCondition's, making the(www\.)match optional with?.The[NC]flag is thenocaseflag.To clear the querystring, append?to the end of the rewrite URLRewriteCond %{HTTP_HOST} ^(www\.)?washington\. [NC] RewriteRule ^(.*)$ http://www.mysite.com/washington? [R=301,L]
I need to redirect all subdomain requests to be redirected to my primary domain in my htaccess. I need it to also include some sort of wildcard redirect.e.g. washington.mysite.com/ redirect to mysite.com/washingtonbut I need to to also redirect any old url on the subdomain to mysite.com/washingtone.g. washington.mysite.com/category.aspx?washington-attractions&CatID=17 redirect to my-site.com/washingtonThis is my code so far:RewriteCond %{HTTP_HOST} ^washington\.mysite\.com$ [OR] RewriteCond %{HTTP_HOST} ^www\.washington\.mysite\.com$ RewriteRule ^(.*)$ "http\:\/\/www\.mysite\.com\/washington/$1" [R=301,L]However it still appends the old URL to the new onee.g. washington.mysite.com/category.aspx?washington-attractions&CatID=17 redirects to my-site.com/washington/category.aspx?washington-attractions&CatID=17Basically I need the redirect washington.mysite.com/*(anything) to my-site.com/washingtonAny suggestions would be much appreciated :)
How do I redirect all subdomain requests to primary domain in htaccess?
As far as I'm aware the only way to show the 404 page from PHP is to explicitly redirect to it. The reason is Apache (or whatever web server you're using) has already successfully located a resource to which to direct the client (the PHP script being executed). If the PHP script can't resolve the client's request then it has to handle the sending of 404 headers and displaying the page itself.You could either redirectheader ("HTTP/1.0 404 Not Found"); header ('Location: http://' . $_SERVER["SERVER_NAME"] . '/404.php');Or you could include the 404 page into the PHP script that wants to trigger a 404.header ("HTTP/1.0 404 Not Found"); include ('/path/to/404.php');EDIT: If you use the first technique (redirection) and want to pass the $_GET to the script so it can determine what's wrong with it, you can do this.header ("HTTP/1.0 404 Not Found"); header ('Location: http://' . $_SERVER["SERVER_NAME"] . '/404.php?' . http_build_query ($_GET));If you include the 404.php file then the $_GET will be available to it already
I would like to redirect users that use a wrong querystring in the URL to a custom error page while ALSO giving a 404 status through the .htaccess directiveErrorDocument 404 http://www.domain.com/404.phpEDIT: this does not give 404 but 302!!! The "http://www.domain.com" causes a redirect. Just the local path gives a 404. See alsohttp://httpd.apache.org/docs/2.0/mod/core.html#errordocumentTherefore I made a script in the request-receiving index.php that determines if the querystring is not valid and if so, gives this command:header("HTTP/1.0 404 Not Found");BUT this does not redirect via the .htaccess directive ErrorDocument but just gives a 404 status to the visitor.And when usingheader("Location: 404.php")you get a 302 status, and when usingheader("Location: 404.php", true, 404)the status is 404 but it does not go to the custom 404.php page.Now I useheader ("Location: ", true, 404); echo "The URL you use doesn't lead to an existing page, etc.";But this was not the original plan... How would I make users that use a wrong querystring in the URL redirect to the custom error page while also giving a 404 status through the .htaccess directive ErrorDocument, or is this not possible?
How redirect wrong querystring to custom errorpage + 404 status
You need to do a check that the old URL with thephpin itis actually being requestedby matching against%{THE_REQUEST}, otherwise it'll redirect loop forever (e.g. user goes to team.php, serve redirects to teams, browser requests teams, server rewrites as teams.php, server sees "teams.php" and redirects to teams, browser requests teams, server rewrites as teams.php, etc. etc.)RewriteEngine On # redirect when the user actually requests for teams.php RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /teams\.php\?league=([^&]+)&team=([^&]+)&year=([^&]+)&tab=([^\ ]+) RewriteRule ^teams\.php$ /teams/%1/%2/%3/%4? [R=301,L] # internally rewrite any /teams/ URI RewriteCond %{REQUEST_URI} !^(css|js|img)/ RewriteRule ^teams/([^/]*)/([^/]*)/([^/]*)/([^/]*)$ teams.php?league=$1&team=$2&year=$3&tab=$4 [L]
I successfully changed my URLs from ugly ones with several parameters in the querystring to clean looking ones with the help of mod rewrite. However, there are many url's for my site. Rather than go back and edit the href attribute on each and every one of my anchor tags, I tried to write a redirect function in the .htaccess file that automatically redirects the old url to the new one.In my .htaccess file, I have the following:RewriteEngine On Redirect teams.php?league=$1&team=$2&year=$3&tab=$4 teams/(.*)/(.*)/(.*)/(.*) RewriteCond %{REQUEST_URI} !^(css|js|img)/ RewriteRule ^teams/([^/]*)/([^/]*)/([^/]*)/([^/]*)$ teams.php?league=$1&team=$2&year=$3&tab=$4 [L]No luck though... any thoughts?Thanks
Mod Rewrite redirect URL with query string to pretty url
The particular behavior you're asking about comes about because the ruleRewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]is a 301 redirect; it instructs the browser to initiate a completely new HTTP request. TheLonly causes (can only cause) it to be the last rule executed forthat request; the new request comes in with the correct hostname and proceeds onward.
My .htaccess file is as follows:Options -Multiviews RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ $1.phpIt works, but I'm wondering how it works. For example, if I type inexample.com/main, I get the file atwww.example.com/main.php. How do I get the.phpextension if the code tells the rewriting to stop after adding thewww.to the beginning ofexample.com?Edit:Or should I create a unique ID only for the purpose of logging in the remembered user?
How does this mod_rewrite code resolve properly?
This should work:RewriteCond %{REQUEST_URI} !^/?PAGEX.aspx$ RewriteRule .* http://destinationwebsite.com [R=301,L]
I want to forward everything on site X (http://example.com) to Site Y (http://destinationwebsite.com) except "PAGEX.aspx"(http://example.com/PAGEX.aspx?callback=7259%2F7062434327_9fbc6da0cd)
htaccess: redirect if not match
If you want to log the IP and then serve the image anyway, then something like this might do:.htaccess file:RewriteEngine on RewriteRule images/(.+)\.(jpg|gif|png) images.php?image=$1.$2images.php:<?php $ipAddress = $_SERVER['REMOTE_ADDR']; $statement=$db->prepare("INSERT INTO `ipaddress` (`ip` ) VALUES (?)"); $statement->execute(array($ipAddress)); $ext = strtolower(end(explode('.', $_GET['image']))); if($ext == 'gif') { $type = "gif"; } else if($ext == 'jpg') { $type = "jpeg"; } else if($text == 'png') { $type = "png"; } else { $type = "binary"; } header("Content-type: image/$type"); readfile("images/" . $_GET['image']); ?>You may need to adjust paths here and there to make sure all files are correctly pointed to, both in.htaccessand inimages.php.
I am trying to track ip address of hotlinkers using php and htaccess..htaccess file:RewriteEngine on RewriteRule images/(.+)\.(jpg|gif|png) images.phpimages.php?php $ipAddress = $_SERVER['REMOTE_ADDR']; $statement=$db->prepare("INSERT INTO `ipaddress` (`ip` ) VALUES (?)"); $statement->execute(array($ipAddress)); ?>Now a user request a image like this www.domain.com/images/image.jpg it will redirect to images.php and track their ips. The problem i am facing here is inside my page is not showing image (reason htaccess redirect it to images.php). How can i fix this problem?Here is the link of previous question regarding this issue:I am not expert in htaccess so need more explanationsThanks
How can i track hot linkers ip address using php and htaccess
Nope there is no way to retrieve it.RewriteBaseitself is not a rule, it is just a string that will be cut off the url before rewriting process.So php just doesn't have any chances to retrieve itPS: personally I cannot think of any reason to rely on its value. Probably you're trying to solve some issue in a wrong way.PPS: I put answer to the @Adi's question from the comments here:It is not possible to just read the.htaccessbecause of:There might be several.htaccessfiles in different directories and you cannot be sure which one has been usedRewriteCondcan be specified inhttpd.conf
I'm wondering if there is a method in PHP for getting the values of specific rules set out in a .htaccess file? In basic terms: if there is a (for example)RewiteBaserule, what is it's value?There does not seem to be anything to serve this in the Manual for$_SERVER, perhapsfread()?
Get value of .htaccess RewriteBase param in PHP
In Cake's root.htaccessfile you can put:RewriteRule ^forum/ - [L]If you insert this just beforeRewriteRule ^$ app/webroot/ [L]then it will allow requests tohttp://www.example.com/forumto go straight to phpBB, bypassing Cake.
I have CakePHP files in my web root (supposehttp://www.example.com/).Now, I wish to host a phpBB3 installation in a folder called "forum" under my web root. So when somebody accesses (http://www.example.com/forum), they can use phpBB.How do I achieve this? I've tried looking into CakePHP documentation for routes configuration, but couldn't find anything related to this.I'm pretty sure this has something to do with.htaccessbut not sure exactly what.Note - I tried creating a folder calledforumunderapp/webrootbut this often redirects tohttp://www.example.com/app/webroot/forum.
Hosting phpBB3 in a subfolder alongside CakePHP
Found an answer!Full answer courtesy of user 'kostasz' athttp://bit.ly/NSDWE2in comments.The hint was indeed the infinite redirect - usingRewriteBase /cakewas not the correct base URL.To fix this issue, addRewriteBase /to each of the.htaccessfiles in/,/app/, and/app/webroot/.
I have a LAMP server configured withDocumentRoot /var/wwwchanged toVirtualDocumentRoot /var/www/%-3/in the Apache2 config file - this allows me to automatically map/var/www/<subdomain>to<subdomain>.example.com.I'm currently in the process of learning CakePHP (2.x), with Cake in directory/var/www/foo/; I've noticed that the URLS aren't redirecting properly, and am attempting to resolve this issue; as perhttp://bit.ly/KmEhHl, I've modified the default .htaccess file to (among other things):RewriteBase /cake RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L]But this raises a 500 Internal Server Error - checking Apache2'serror.logandrewrite.log, this is because.htaccessis causing an infinite redirect, and is appendingapp/webrootto the URI.From my understanding, theLflag here should indicate 'last rule' - I'm assuming that this error is due to my poor understanding ofmod_rewrite, but I'm not sure exactly where this is happening. Would the error be because of some other latent issue with this setup? I'm aware that there have been several questions on this already, and will update if any new information can be found on my end. Any help would be greatly appreciated!
CakePHP and VirtualDocumentRoot issue
You need to configure Apache so it knows that you want .phtml files to be treated as PHP. See step 8 ofthe PHP install guide.<FilesMatch "\.ph(p[2-6]?|tml)$"> SetHandler application/x-httpd-php </FilesMatch>... but .phtml is the file extension used for PHP 2. You should probably audit them, bring them up to modern PHP coding practises and rename them to follow current conventions.
I want to render a .phtml file through Apache, however when I try, it renders the page as text and not as html.In my vhost configuration, if I try to render an index.php, it executes properly. But when I change the DirectoryIndex to index.phtml and try to render the index.phtml present in the public directory it just renders text.The vhost Config is:codeServerName parminder.com DocumentRoot "C:/workspace/parminder_local_net/public" ErrorLog logs/parmindercom.logOptions Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all DirectoryIndex index.phtml *What else do I need to configure for this to work? Do I need to use .htaccess? What is the basic concept?
How to render a .phtml file through apache