In general, it is determined by the tile on which the attacked unit is standing.
So, in case of melee units, it's where the combat takes place - i.e. in the hex containing the defending unit.
In case of ranged units, attack bonuses depend on the hex on which the target is standing.
No, you cannot force ranged units to perform a melee attack (but they can range-attack a unit in the adjacent hex), and this includes melee attacking to capture a city - so always bring some melee units to a siege.
They can be engaged in melee if an enemy attacks them with a melee unit, but this uses the ranged unit's strength value, instead of ranged strength, which is usually much lower - expect them to lose against unit of a similar technological level; it's best to keep them out of melee range.
The exceptions are the Gatling Gun and Machine Gun units introduced by Gods & Kings, they are explicitly designed for getting up close and personal - having only a single tile of range and matching strength and ranged strength scores that compare to the melee units of their time.
The same applies for all updated version of the archer, all updated version of the catapult, and all ranged combat ships/submarines - any 'bombarding' ranged unit of any type, essentially.
(Note: the Gods and Kings expansion divides ships in to melee and ranged, performing the same functions as their land equivalents, so this distinction is now important at sea too, especially since the melee naval units can capture now cities).
All these units can, I believe, capture civilians by entering the tile they are on - and, in the case of ships, they can destroy any embarked unit with the same method (Note: this has changed in the Gods and Kings expansion; embarked units can defend themselves and are not automatically destroyed). This always counts as the unit performing an attack, so they lose that attack until the next turn.
Best Answer
The ranged combat specific promotions are wasted if the unit is upgraded to a melee unit.